Mobx 中可观察的私有(private)属性

标签 observable private mobx

我对 Mobx 商店中的可观察私有(private)属性(property)有疑问。问题是带有 getter 和 setter 的可观察私有(private)属性不起作用,而公共(public)可观察属性工作得很好。为什么会这样?我交替测试了私有(private)和公共(public)属性(#privateSelectedTypeselectedType)以执行相同的操作。

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 更改为公共(public)字段 _publicSelectedType 即可使此代码正常工作。在我看来,mobx 对 JavaScript 私有(private)字段不起作用或以不同方式起作用。

最佳答案

编辑后的答案:

在评论中对您的代码进行一些研究和调试后,发现 mobx 在内部试图装饰 CarsStore 的原型(prototype)属性,其中私有(private)字段缺失:

enter image description here

这样做的原因是,在这个提案语法中,私有(private)字段只能从类的主体中看到和访问,因为它们被记录为元数据并且只能从引擎访问。更多信息在此 link(point 5) .我希望现在这能回答您的问题。

关于Mobx 中可观察的私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60995261/

相关文章:

javascript - 仅在 react 组件渲染功能之外使用 mobx 存储

javascript - 如何从 mobx 对象中获取普通对象?

Android LiveData Observer 没有被第二次触发

JavaFX 可观察 Bean 生成器?

调用了 Angular ngrx + Firebase OAuth 操作但没有效果

ios - Swift XCTest 访问私有(private)变量

javascript - Observable toPromise 在调用完整回调之前已解析

java - 更改引用而不显式更改其引用

java - 父类中的私有(private)字段 - java

javascript - 莫布克斯 : Is there a way to find whether a form isDirty using a mobx Utility