我正在使用带有JS和mobx
decorate
方法的最新create-react-app设置。
import { observable, action, decorate } from 'mobx'
class UserStore {
users = []
currentUser = {}
setUsers(value) {
this.users = value
}
}
decorate(UserStore, {
users: observable,
currentUser: observable,
setUsers: action
})
export default UserStore
我可以使用存储并读取空的users
和currentUser
可观察对象,但是当我尝试使用setUsers
操作时,收到以下错误:
TypeError: Cannot set property 'users' of undefined
看起来好像是this
,但未定义,但这是大多数MobX教程显示的常用方式,不应引发错误...
[当将MobX与原始JavaScript一起使用时,不同的上下文可能会使您感到困惑... MobX引入了bound action
s,以简化此操作。
使用action
的正确装饰是:
action.bound
或者我们可以使用lambda函数来确保上下文正确:
setUsers: action.bound
任何一种更改都将确保setter函数的上下文正确,并且可以使用类setUsers = value => {
this.users = value
}
。请查看this
了解更多详细说明。