问题描述
我的应用程序停止更新可观察到的变化,我快疯了,试图找出原因.下面的代码仅显示计数器:5"在屏幕上,即使控制台显示它正在更新.package.json 的相关部分是:
My app stopped updating on observable changes and I'm going crazy trying to figure out why. The code below shows only "Counter: 5" on the screen even though the console shows that it is updating. The relevant parts of package.json are:
{
"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),而且我不得不将副作用提取到这样的动作上下文中:
Turns out I needed to call makeObservable(this) in the constructor of my TestModel, plus I had to pull out the side effect into an action context like this:
@action incrementCounter = () => {
this.counter++;
console.log(this.counter)
}
start() {
setInterval(this.incrementCounter, 1000);
}
推荐答案
由于 [email protected]
装饰器是不够的.您必须使用 makeObservable
也是.
Since [email protected]
decorators are not enough. You have to make your class observable manually with makeObservable
as well.
import { observable, makeObservable } from "mobx";
class TestModel {
@observable counter = 5;
constructor() {
makeObservable(this);
}
start() {
setInterval(() => {this.counter++; console.log(this.counter)}, 1000);
}
}
这篇关于当可观察到的变化时,mobx 观察者突然不重新渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!