React MobX - 装饰器 + useObserver 不重新渲染

React MobX - decorators + useObserver don't re-render

我无法使用 MobX 使 React 重新渲染。 我正在按照文档设置所有内容。我的 class 包含 actionobservable 装饰器。我尝试使用 useObserver hookobserver HOC 连接 React 组件,它只是 不会重新渲染 .

片段:

import React from "react";
import ReactDOM from "react-dom";
import { action, observable } from "mobx";
import { observer, useObserver } from "mobx-react-lite";

class Timer {
  @observable secondsPassed: number = 0;

  @action increaseTimer() {
    console.log("here");
    this.secondsPassed += 1;
  }
}

const myTimer = new Timer();

setInterval(() => {
  myTimer.increaseTimer();
}, 1000);

const TimerView = ({ timer }: { timer: Timer }) => {
  return useObserver(() => <div>{timer.secondsPassed}</div>);
};

ReactDOM.render(<TimerView timer={myTimer} />, document.body);

https://codesandbox.io/s/minimal-observer-forked-gif4q?file=/src/index.tsx

我试图让它与装饰器一起工作,我做错了什么?

您需要使用 Provider 包装您的应用并将商店作为道具传递

import { Provider } from 'mobx-react';


ReactDOM.render(
 <Provider {myTimer}> <TimerView timer={myTimer} /> </Provider>,
  document.body
);

经过 4 小时的研究。 我团队的项目使用 MobX 版本 4.x 并且代码库使用装饰器作为上面的示例。

但是

MobX before version 6 encouraged the use of ES.next decorators to mark things as observable, computed and action. However, decorators are currently not an ES standard, and the process of standardization is taking a long time. It also looks like the standard will be different from the way decorators were implemented previously. In the interest of compatibility we have chosen to move away from them in MobX 6, and recommend the use of makeObservable / makeAutoObservable instead.

MobX Documentation

这意味着,MobX 现在需要使用 makeObservable(this):

在构造函数中将 class 声明为可观察的
import { makeObservable } from "mobx";

class Timer {
  @observable secondsPassed: number = 0;

  @action increaseTimer() {
    this.secondsPassed += 1;
  }

  // THIS IS IMPORTANT FROM MOBX 6.X ONWARDS
  constructor() {
    makeObservable(this);
  }
}

来自文档:

MobX before version 6 did not require the makeObservable(this) call in the constructor, but because it makes the implementation of decorator simpler and more compatible, it now does. This instructs MobX to make the instances observable following the information in the decorators -- the decorators take the place of the second argument to makeObservable.

进一步阅读 MobX