当可观察的变化时,mobx 观察者突然不重新渲染

mobx observer suddenly not rerendering when observable changes

我的应用停止更新可观察到的变化,我快要发疯了,想找出原因。下面的代码仅在屏幕上显示“Counter: 5”,即使控制台显示它正在更新。 package.json的相关部分是:

{
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
  },
  "dependencies": {
    "mobx": "^6.0.4",
    "mobx-react": "^7.0.5",
    "react": "17.0.0",
    "react-dom": "17.0.0",
    "react-icons": "^4.1.0",
    "react-router-dom": "^5.2.0",
    "typescript": "^4.0.3",
  },
  "devDependencies": {
    "babel-preset-mobx": "^2.0.0",
    "react-app-rewire-yaml": "^1.1.0",
    "react-scripts": "^4.0.1"
  }
}

import React from "react";
import ReactDOM from "react-dom";
import "./index.css"
import { inject, observer, Provider } from "mobx-react";
import { observable } from "mobx";

class TestModel
{
    @observable counter = 5;
    start() {
        setInterval(() => {this.counter++; console.log(this.counter)}, 1000);
    }
}

@inject("testModel")
@observer 
class TestPage extends React.Component<{testModel?: TestModel}> 
{
    render() {
        return <div><h1>Counter: {this.props.testModel.counter}</h1></div>
    }
}

const theTestModel = new TestModel();
theTestModel.start();

ReactDOM.render(
    <Provider testModel={theTestModel}> 
        <TestPage />
    </Provider>,
    document.getElementById("root")
);

编辑:

原来我需要在我的 TestModel 的构造函数中调用 makeObservable(this),而且我必须将副作用提取到这样的操作上下文中:

@action incrementCounter = () => {
    this.counter++; 
    console.log(this.counter)
}

start() {
    setInterval(this.incrementCounter, 1000);
}

Since mobx@6.0.0 decorators are not enough. You have to make your class observable manually with makeObservable 还有。

import { observable, makeObservable } from "mobx";

class TestModel {
    @observable counter = 5;

    constructor() {
        makeObservable(this);
    }

    start() {
        setInterval(() => {this.counter++; console.log(this.counter)}, 1000);
    }
}