最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactMobX: Store values are undefined? - Stack Overflow

programmeradmin1浏览0评论

My MobX autorun function logs out undefined for both of the values here. Also, in my ponents that import user from '../../stores/UserStore, the instances that I use {user.userName} all show nothing at all.

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
})

My MobX autorun function logs out undefined for both of the values here. Also, in my ponents that import user from '../../stores/UserStore, the instances that I use {user.userName} all show nothing at all.

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
})
Share Improve this question asked Sep 14, 2016 at 2:26 Colton ColcleasureColton Colcleasure 5185 silver badges10 bronze badges 4
  • did you mean new UserStore() ? – azium Commented Sep 14, 2016 at 2:31
  • It works for me. Try changing the fields of user in the console. Maybe you are running into this issue? – Tholle Commented Sep 14, 2016 at 8:21
  • I came to find that the problem had to do with my usage of create-react-app. I was able to get the observer/observable functions to work, but without decorators. observer(export default class MyComponent extends Component { ... and class MyStore { myValue = observable('some value here') } – Colton Colcleasure Commented Sep 15, 2016 at 13:38
  • Do decorators in general not work for you? You may have to manually install the Babel plugin for it – Peter Gelderbloem Commented Nov 3, 2016 at 6:49
Add a ment  | 

2 Answers 2

Reset to default 5

If you want to use decorators with create-react-app you will need to eject the app. "Running npm run eject copies all the configuration files and the transitive dependencies." https://github./facebookincubator/create-react-app Also I found you need to put transform-decorators-legacy plugin first like so:

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

After you do all this. The following will work and has been tested.

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

Just moving the following to the top of the plugins array in the babel.config.js file solved the problem for me.

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

评论列表(0)

  1. 暂无评论