Search code examples
observableprivatemobx

Observable private property in Mobx


I have a problem with observable private property in the Mobx store. The thing is that observable private property with getter and setter doesn't work, while a public observable property works perfectly fine. Why is so? I tested both private and public property (#privateSelectedType and selectedType) interchangeably to do the same thing.

EDIT2: I've created a codesandbox to better show the case: https://codesandbox.io/s/tender-pond-kglzr?file=/src/carsStore.js

Here is a code that exemplifies the situation. I use this store to display all types and mark the selectedType:

class CarsStore {
  #types = ["defaultType", "type1", "type2"];
  #privateSelectedType = "defaultType";
  selectedType = "defaultType";

  otherThings = [];

  get types() {
    return this.#types;
  }

  get privateSelectedType() {
    return this.#privateSelectedType;
  }

  set privateSelectedType(selectedType) {
    this.#privateSelectedType = selectedType;
    // call function updating otherThings, that's why I want to use setter in this store
    this.#updateOtherThings();
  }

  #updateOtherThings = () => {
    //update otherThings
  }
}

decorate(CarsStore, {
  "#types": observable,
  "#privateSelectedType": observable,
  selectedType: observable,
  otherThings: observable
});

EDIT: Simply changing all occurrences of #privateSelectedType to public field _publicSelectedType makes this code working. It seems to me that mobx simply doesn't work or works differently with JavaScript private fields.


Solution

  • This is a known limitation that is documented by MobX. Fortunately there is a workaround syntax:

    https://mobx.js.org/observable-state.html#limitations

    I've used it many times and it works just fine.