mobx-react-lite:无法读取未定义的属性
mobx-react-lite: Cannot read properties of undefined
我有一个简单的组件,它只是在屏幕上增加值,但我收到一个错误:Uncaught TypeError: Cannot read properties of undefined (reading 'value') at increment (initialState.js:11:7)
。
App.js:
return (
<IncrementButton store={Store} />
);
IncrementButton.js:
import {observer} from 'mobx-react-lite';
import React from 'react';
export const IncrementButton = observer(({store}) => {
return (
<div>
<button onClick={store.rebate.increment}>Increase</button>
<h1>{store.rebate.value}</h1>
</div>
);
});
rootStore.js:
import {makeAutoObservable} from 'mobx';
import {initialState} from './initialState';
class RootStore {
states = initialState;
constructor() {
makeAutoObservable(this);
}
increaseNumber = () => {
this.states.rebate.increment();
};
}
const Store = new RootStore();
export default Store.states;
initialState.js:
export const initialState = {
rebate: {
id: 1,
name: 'Example',
value: 3000,
increment() {
this.value = this.value++;
},
},
};
我也在学习新技巧,因为我从 mobx-react-lite
开始,而且只有 mobx-react-lite
。似乎很难找到仅关于 mobx-react-lite
的文档。非常感谢!!
this
是 undefined
在你的 initialState
的“方法”中。
从initialState
中删除increment
并将increaseNumber
写成
increaseNumber = () => {
this.states.rebate.value += 1;
}
我有一个简单的组件,它只是在屏幕上增加值,但我收到一个错误:Uncaught TypeError: Cannot read properties of undefined (reading 'value') at increment (initialState.js:11:7)
。
App.js:
return (
<IncrementButton store={Store} />
);
IncrementButton.js:
import {observer} from 'mobx-react-lite';
import React from 'react';
export const IncrementButton = observer(({store}) => {
return (
<div>
<button onClick={store.rebate.increment}>Increase</button>
<h1>{store.rebate.value}</h1>
</div>
);
});
rootStore.js:
import {makeAutoObservable} from 'mobx';
import {initialState} from './initialState';
class RootStore {
states = initialState;
constructor() {
makeAutoObservable(this);
}
increaseNumber = () => {
this.states.rebate.increment();
};
}
const Store = new RootStore();
export default Store.states;
initialState.js:
export const initialState = {
rebate: {
id: 1,
name: 'Example',
value: 3000,
increment() {
this.value = this.value++;
},
},
};
我也在学习新技巧,因为我从 mobx-react-lite
开始,而且只有 mobx-react-lite
。似乎很难找到仅关于 mobx-react-lite
的文档。非常感谢!!
this
是 undefined
在你的 initialState
的“方法”中。
从initialState
中删除increment
并将increaseNumber
写成
increaseNumber = () => {
this.states.rebate.value += 1;
}