React+添加componentdidmount()方法后,mobx观察者类组件不dy rerender
我发现了一种非常奇怪的MOBX行为,我不知道为什么会发生。试图谷歌搜索它,但没有发现我面临的问题。
因此,我有一个非常简单的MOFX商店,用于计数器:
import { makeAutoObservable } from "mobx";
class CounterStore {
constructor(initialState) {
this.count = initialState ?? 0;
makeAutoObservable(this);
}
dec = () => this.count--;
inc = () => this.count++;
get color() {
return this.count > 0 ? "green" : this.count < 0 ? "red" : "black";
}
}
export default CounterStore;
contrymobx
是React类组件:
import { observer } from "mobx-react";
import { Component } from "react";
import CounterStore from "../../stores/CounterStore";
const store = new CounterStore(1);
const CounterMobx = observer(
class extends Component {
render() {
return (
<div>
<button onClick={store.dec}>-</button>
<span style={{ color: store.color }}>{store.count}</span>
<button onClick={store.inc}>+</button>
</div>
);
}
}
);
export default CounterMobx;
一切正常,直到我添加ComponentDidMount()
lifecycle方法到contrymobx
组件:
componentDidMount() {
console.log(store);
}
添加ComponentDidMount()
之后停止跟踪商店中可观察的值,
我做错了什么还是这是一个错误?
"react": "^18.1.0",
"mobx": "^6.6.0",
"mobx-react": "^7.5.0",
I've found a very strange MobX behavior and I've no idea why it happens. Tried to google it but found nothing about the issue I've faced.
So, I've got a very simple MobX store for the counter:
import { makeAutoObservable } from "mobx";
class CounterStore {
constructor(initialState) {
this.count = initialState ?? 0;
makeAutoObservable(this);
}
dec = () => this.count--;
inc = () => this.count++;
get color() {
return this.count > 0 ? "green" : this.count < 0 ? "red" : "black";
}
}
export default CounterStore;
And the CounterMobx
which is React class component:
import { observer } from "mobx-react";
import { Component } from "react";
import CounterStore from "../../stores/CounterStore";
const store = new CounterStore(1);
const CounterMobx = observer(
class extends Component {
render() {
return (
<div>
<button onClick={store.dec}>-</button>
<span style={{ color: store.color }}>{store.count}</span>
<button onClick={store.inc}>+</button>
</div>
);
}
}
);
export default CounterMobx;
Everything works just fine until I add componentDidMount()
lifecycle method to the CounterMobx
component:
componentDidMount() {
console.log(store);
}
After adding componentDidMount()
when I try to change the count value with actions (by clicking "-" or "+" button) nothing happens, component stopped tracking the observable values from store
Is there something I'm doing wrong or this is a bug?
"react": "^18.1.0",
"mobx": "^6.6.0",
"mobx-react": "^7.5.0",
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是 react 18 and react 18 and
&lt react.StrictMode&gt;
。如果删除组件树顶部的
&lt; react.strictmode&gt;
组件现在应该可以使用。This seems to be a problem with React 18 and
<React.StrictMode>
. If you remove the<React.StrictMode>
component at the top of your component tree for now it should work.