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

Can I manually trigger observers of specific properties in MobX?

我有一个对象,它有一些持久保存在 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++;
  }
}

有没有更好的方法来实现这个?

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

class MyClass {
  @observable attribute = Cookie.get("attribute")

  constructor() {
    autorun(() => Cookie.set("attribute", this.attribute))
  }
}