基本使用

doc

https://www.mobxjs.com/#%E4%B8%80%E4%B8%AA%E7%AE%80%E5%8D%95%E7%9A%84%E4%BE%8B%E5%AD%90

  1. import { makeAutoObservable } from "mobx";
  2. import { observer } from "mobx-react";
  3. // 对应用状态进行建模。
  4. class Timer {
  5. // 自动实现了旧版本的 @observable
  6. secondsPassed = 0;
  7. constructor() {
  8. makeAutoObservable(this);
  9. }
  10. // 自动实现了旧版本的 @action
  11. increase() {
  12. this.secondsPassed += 1;
  13. }
  14. reset() {
  15. this.secondsPassed = 0;
  16. }
  17. }
  18. const myTimer = new Timer();
  19. // 每秒更新一次‘已过秒数:X’中的文本。
  20. setInterval(() => {
  21. myTimer.increase();
  22. }, 1000);
  23. // 构建一个使用 observable 状态的“用户界面”。
  24. const TimerView = observer(({ timer }: any) => (
  25. <button onClick={() => timer.reset()}>已过秒数:{timer.secondsPassed}</button>
  26. ));
  27. const App = () => <TimerView timer={myTimer} />;
  28. export default App;

继承模板

import { useEffect } from "react";

import {
  observable,
  computed,
  action,
  override,
  configure,
  makeObservable,
} from "mobx";

configure({ enforceActions: "always" });

class Parent {
  // Annotated instance fields are NOT overridable
  observable = 200;
  arrowAction = () => {};

  extraFilterParams: any = {};

  // Non-annotated instance fields are overridable
  overridableArrowAction = action(() => {});

  // Annotated prototype methods/getters are overridable
  action() {}
  actionBound() {}
  get computed() {
    return "computed";
  }

  constructor() {
    makeObservable(this, { // makeAutoObservable 不能再继承中使用,makeObservable手动设置为可观察数据
      observable: observable,
      arrowAction: action,
      action: action,
      actionBound: action.bound,
      computed: computed,
    });
  }
}

class Child extends Parent {
  /* --- 继承来的定义 --- */
  // 抛出 - TypeError: Cannot redefine property, field不能被继承
  // observable = 5;
  // arrowAction = () = {}

  // OK - not annotated
  overridableArrowAction = action(() => {});

  // OK - prototype
  actionBound() {}
  get computed() {
    return "heihei";
  }

  /* --- 新的定义 --- */
  childObservable = 300;
  childArrowAction = () => {};
  childAction() {}
  childActionBound() {}
  get childComputed() {
    return "child computed";
  }

  constructor() {
    super();
    makeObservable(this, {
      // 继承来的
      action: override,
      actionBound: override,
      computed: override,
      // 新的
      childObservable: observable,
      childArrowAction: action,
      childAction: action,
      childActionBound: action.bound,
      childComputed: computed,
    });
  }
}

const App = () => {
  useEffect(() => {
    const mParent = new Parent();
    console.log("mParent: ", mParent);

    const mChild = new Child();
    console.log("mChild: ", mChild);
  }, []);

  return <div></div>;
};

export default App;

doc

https://www.mobxjs.com/subclassing

对使用子类的支持是有限制的。 最值得注意的一点是你只能重新定义原型中的 actions/flows/computeds——你不能重新定义字段声明。 在子类中请使用 override 注释被重新定义的methods/getters - 见下例。 请凡事从简,并优先考虑组合(而非继承)。