Reactjs Can';不要让MobX、打字脚本、反应和动作正常工作
我一直在尝试一个看似简单的例子,但未能使用MobX、React、TypeScript和actions。没有严格模式,一切都可以工作,但我宁愿使用严格模式 我得到的错误是:Reactjs Can';不要让MobX、打字脚本、反应和动作正常工作,reactjs,typescript,mobx,Reactjs,Typescript,Mobx,我一直在尝试一个看似简单的例子,但未能使用MobX、React、TypeScript和actions。没有严格模式,一切都可以工作,但我宁愿使用严格模式 我得到的错误是: Uncaught Error: [mobx] Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this
Uncaught Error: [mobx] Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: AppState@1.timer
at invariant (mobx.module.js:2704)
at fail$1 (mobx.module.js:2699)
at checkIfStateModificationsAreAllowed (mobx.module.js:3303)
at ObservableValue.prepareNewValue (mobx.module.js:997)
at ObservableObjectAdministration.write (mobx.module.js:1093)
at AppState.set [as timer] (mobx.module.js:1257)
at AppState.set [as timer] (mobx.module.js:143)
at new AppState (index.tsx:26)
at eval (index.tsx:66)
不幸的是,我不知道我应该把@action(或@action.bound)放在哪里才能让它工作,或者我做错了什么
这是我的代码:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import * as MobX from 'mobx';
import * as MobXReact from 'mobx-react';
import DevTools from 'mobx-react-devtools';
MobX.configure({
enforceActions: 'strict'
});
class AppState {
@MobX.observable
public timer = 0;
public constructor() {
setInterval(() => {
this.incrTimer();
}, 1000);
}
@MobX.action
public incrTimer() {
this.timer += 1;
}
@MobX.action
public resetTimer() {
this.timer = 0;
}
}
@MobXReact.observer
class TimerView extends React.Component<{appState: AppState}, {}> {
render() {
return (
<div>
<button onClick={this.onReset}>
Seconds passed: {this.props.appState.timer}
</button>
<DevTools/>
</div>
);
}
onReset = () => {
this.props.appState.resetTimer();
}
};
const appState = new AppState();
const rootNode = document.body.appendChild(document.createElement('div'));
ReactDOM.render(<TimerView appState={appState} />, rootNode);
import*as React from'React';
从“react dom”导入*作为react dom;
从“MobX”导入*作为MobX;
从“mobx react”导入*作为MobXReact;
从“mobx react DevTools”导入DevTools;
MobX.configure({
执法行动:“严格”
});
类AppState{
@可观察的
公共计时器=0;
公共构造函数(){
设置间隔(()=>{
this.incrTimer();
}, 1000);
}
@MobX.action
公共增量(){
这个计时器+=1;
}
@MobX.action
公共重置计时器(){
这个计时器=0;
}
}
@MobXReact.observer
类TimerView扩展了React.Component{
render(){
返回(
秒数已过:{this.props.appState.timer}
);
}
onReset=()=>{
this.props.appState.resetTimer();
}
};
const appState=新的appState();
const rootNode=document.body.appendChild(document.createElement('div'));
render(,rootNode);
更新:在根据答案进行了更多的修补之后,发现错误来自TS发出的JS。公共计时器=0this.timer=0的形式发出code>属性代码>内部构造函数
,这就是爆炸的原因
删除赋值并添加另一个函数已通过错误,但为属性初始化执行此操作似乎不必要。问题很可能是您正在构造函数中设置计时器。在构造函数完成之前,MobX不会包装属性,因此当构造函数设置此计时器回调时,它会获取对真实incrTimer的引用,而不是MobX.action(incrTimer)。如果您将计时器安装移动到构造函数之外的方法,然后在构建对象后调用该方法,则此严格警告将消失。例如:
const appState = new AppState();
appState.setupTimer();