我可以在 MobX 中手动触发特定属性的观察器吗?

Can I manually trigger observers of specific properties in MobX?

本文关键字:属性 观察 MobX 我可以      更新时间:2023-09-26

我有一个对象,它有一些可观察的属性,这些属性持久保存在cookie中:

class MyClass {
  @observable attribute = Cookies.get("attribute");
  @action updateAttribute(newValue) {
    this.attribute = newValue;
    Cookies.set("attribute", newValue);
  }
}
var obj = new MyClass();

这显然不理想,因为现在我将数据保存在两个地方(属性和 cookie)。理想情况下,我很想做这样的事情:

class MyClass {
  @computed get attribute() {
    return Cookies.get("attribute");
  }
  @action updateAttribute(newValue) {
    Cookies.set("attribute", newValue);
    // Somehow mark the computed property `this.attribute` as dirty.
  }
}

这样的解决方案可能有效:

class MyClass {
  @observable _version = 0;
  @computed get attribute() {
    // Read `this._version` to create the dependency.
    this._version;
    return Cookies.get("attribute");
  }
  @action updateAttribute(newValue) {
    Cookies.set("attribute", newValue);
    this._version++;
  }
}

有没有更好的方法来实现这一目标?

我认为您的解决方案实际上非常好。另一种解决方案是在启动时仅"读取"一次cookie,然后使用autorun来存储cookie:

class MyClass {
  @observable attribute = Cookie.get("attribute")
  constructor() {
    autorun(() => Cookie.set("attribute", this.attribute))
  }
}