我对 Mobx 商店中可观察的私有财产有疑问。问题是带有 getter 和 setter 的可观察私有属性不起作用,而公共可观察属性工作得很好。为什么会这样?我交替测试了私有财产和公共财产(
#privateSelectedType
和 selectedType
)来做同样的事情。
EDIT2:我创建了一个 codesandbox 以更好地展示案例:https://codesandbox.io/s/tender-pond-kglzr?file=/src/carsStore.js
这里有一段代码可以说明情况。我用这家商店展示所有类型并标记
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
});
编辑:只需将所有出现的
#privateSelectedType
更改为公共字段_publicSelectedType
即可使此代码正常工作。在我看来,mobx 根本无法工作或与 JavaScript 私有字段的工作方式不同。
编辑答案:
在评论中对您的代码进行一些研究和调试后,事实证明 mobx 内部正在尝试装饰 CarsStore 的原型属性,其中缺少私有字段missing:
原因是在这个提案语法中私有字段只能从类的主体中看到和访问,因为它们被记录为元数据并且只能从引擎访问。此链接(第5点)中的更多信息。我希望这现在能回答你的问题。