Maciejosas
Maciejosas

Reputation: 107

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.

Upvotes: 4

Views: 3944

Answers (2)

Artemis Prime
Artemis Prime

Reputation: 186

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.

Upvotes: 1

Antoan Elenkov
Antoan Elenkov

Reputation: 781

EDITED ANSWER:

After some research and debugging of your code in the comments, it turns out that mobx internally is trying to decorate the prototype properties of CarsStore, where private fields are missing:

enter image description here

The reason for this is that in this proposal syntax private fields are only visible and reachable from the body of the class, because they are recorded as a metadata and are accessible only from the engine. More info in this link(point 5). I hope this answers your question now.

Upvotes: 2

Related Questions