我在Mobx商店中可观察到的私有财产有问题。事实是,带有getter和setter的可观察私有财产不起作用,而公共可观察财产则很好。为什么会这样呢?我同时测试了私有财产和公共财产(#privateSelectedType
和selectedType
)以完成相同的工作。
EDIT2 :我创建了一个代码框以更好地显示这种情况: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私有字段中根本无法工作或工作不同。
答案 0 :(得分:1)
修改后的答案:
在对注释中的代码进行了一些研究和调试之后,事实证明,mobx在内部尝试装饰CarsStore的原型属性,其中私有字段丢失:
这样做的原因是,在此提案语法中,私有字段仅在类的正文中可见且可访问,因为私有字段被记录为元数据并且只能从引擎访问。 link(point 5)中的更多信息。我希望这能回答您的问题。