React / MobX:商店值未定义?

时间:2016-09-14 02:26:54

标签: javascript reactjs mobx

我的MobX自动运行功能会在此处为这两个值注销undefined。另外,在import user from '../../stores/UserStore的我的组件中,我使用{user.userName}的实例都没有显示任何内容。

import { observable, autorun } from 'mobx'

class UserStore {
  @observable userName = "tommy";
  @observable arr = [0,1]
}

const user = window.user = new UserStore

export default user;


// user.userName = "timmy"; // works, but not observable.

autorun(() => {
  console.log(user.userName) // undefined
  console.log(user.arr) // undefined
})

2 个答案:

答案 0 :(得分:2)

如果您想在deco-react-app中使用装饰器,则需要弹出应用程序。 “运行npm run eject会复制所有配置文件和传递依赖项。https://github.com/facebookincubator/create-react-app我还发现你需要首先放置transform-decorators-legacy插件:

plugins: ['transform-decorators-legacy','transform-class-properties']

完成所有这些之后。以下内容将有效并经过测试。

@observer class Counter extends React.Component {
    @observable count = 0
}

答案 1 :(得分:1)

只需将以下内容移到babel.config.js文件中的plugins数组的顶部即可为我解决问题。

["@babel/plugin-proposal-decorators", { legacy: true }],
["@babel/plugin-proposal-class-properties", { loose: true }],