如何在 Mobx 中执行可观察函数?

How to do an observable function in Mobx?

我有一个 collection 的商店,我希望它是只读的。我想做类似的事情,但我不知道 Mobx 是否提供了一种创建反应函数的方法。

class Store{
  private _col:Mobx.Map;
  ...

  @observable public has(id){
    return _col.has(id);
  }       
}

我在考虑 no-trust-the-client 的游戏架构。所以我不希望我的视图直接访问 _col.

@observe
class MyView extends Component {
  ...
  componentWillMount(){
    this.id = this.props.params.id;
    autorun(()=>{
      this.props.store.has(this.id)
      //do something smart
    }
  }

  ...
}

有什么替代方案?

你可以直接使用

public 有(id){ return _col.has(id); }

对于可观察对象,无论是直接访问还是通过多层间接访问,MobX 都会跟踪它。