如何让 class 个对象在 MobX 中可见?

How to make class objects observable in MobX?

我有一个 class 作为:

class Field{

  constructor(name) {
    this.name= name
    this.otherAttr = null
  }

  changeName(newName) {
    this.name = newName
  }
}


const f = new Field("Charanjit")
f.setName("Singh") // It shoukd reflect in observer 

f.name = "Rahul" // It should also reflect in observer


如何使 f 对象可观察,以便 f 的属性发生任何变化时,都会更新观察者组件。

目前,我收到错误:https://github.com/mobxjs/mobx/issues/1932 如果我使用:

@observable(f)
>>> It shows Error: https://github.com/mobxjs/mobx/issues/1932

查看 MobX 文档,这样做可能是一个很好的方法:

import { observable, action, decorate } from "mobx";

class Field {
    name = '';
    otherAttr = null;

    changeName(name) {
        this.name = name;
    }
}

decorate(Field, {
    name: observable,
    otherAttr: observable,
    changeName: action
})

使用装饰实用程序将属性标记为可观察对象将满足您的需求。 请阅读文档:https://mobx.js.org/best/decorators.html