0

so mobx 6 is out and i am trying to implement a basic store like that :

export class AuthStore {
  rootStore
  value
  constructor(rootStore) {
    makeObservable(this, {
      value:observable
    })
    this.rootStore = rootStore
  }
}

and

class RootStore {
  constructor () {
    this.authStore = new AuthStore(this)
  }
}

const stores = new RootStore()

and i am getting an error : Cannot decorate undefined property: 'value'

but if i will take the AuthStore outside the RootStore

const authStore = new AuthStore()

every thing working fine .. i tried to read more then once the mobx 6t docs but there is nothing about it

would like to know what i am doing wrong ! thanks !

Eran Abir
  • 1,077
  • 5
  • 19
  • 34

1 Answers1

0

The answer lies in the error message -

Cannot decorate undefined property: 'value'

Your value is undefined, and mobx takes issue with that. The easy fix is to initialise your value to null:

export class AuthStore {
  rootStore
  value = null;
  constructor(rootStore) {
    this.rootStore = rootStore

    makeObservable(this, {
      value:observable
    })
  }
}

It's easy to see why you've fallen victim to this - the mobx documentation itself actually leads you to believe that what you did is kosher -

import { makeObservable, observable, computed, action } from "mobx"

class Doubler {
    value

    constructor(value) {
        makeObservable(this, {
            value: observable,
            double: computed,
            increment: action
        })
        this.value = value
    }

    get double() {
        return this.value * 2
    }

    increment() {
        this.value++
    }
}

But if you try this code out, you get the same error :|.

if i will take the AuthStore outside the RootStore every thing working fine

This threw me a little - I couldn't explain why this would happen! But I couldn't reproduce it either - I got the same behaviour no matter where the auth store was initialised.

For some more background - mobx is using Object.getOwnPropertyDescriptor under the hood to try and work out what the value property is - when the value is undefined, this returns:

Object { value: undefined, writable: true, enumerable: true, configurable: true }
gerrod
  • 6,119
  • 6
  • 33
  • 45