2016-11-20 150 views
1

刚开始使用Mobx &反应并无法让商店更新。点击该按钮,它应该更新 '我' 的属性时,我得到错误:React + Mobx:尝试更新商店时'this'为空

Store.js:12 Uncaught TypeError: Cannot set property 'me' of null 

我的店:

import { observable } from 'mobx'; 

class Store { 

    @observable me; 

    constructor() { 
     this.me = 'test'; 
    } 

    change_me(){ 
     this.me = 'test 1'; 
     console.log(this); // null??? 
    } 

} 

const store = new Store(); 

export default store; 

组件:

import React from "react"; 
import { observer } from 'mobx-react'; 

export default class Layout extends React.Component{ 

    render(){ 

     var store = this.props.store; 

     return(
      <div> 
       <button onClick={store.change_me}>{store.me}</button> 
      </div> 
     ) 

    } 
} 

我可能错过了一些这是如何工作的基本部分,但无法弄清楚。

回答

1

我不知道mobxonClick={store.change_me}是一个问题,因为您正在使用类的方法作为函数(没有this)。你将不得不使用类似:

onClick={event => store.changeMe(event)} 

否则store绑定丢失。

同样可能的,但以下可读:

onClick={store.changeMe.bind(store)} 
+0

感谢您的输入 - 我已经修复它,我把它分离成组件内的一个函数。但现在我有另一个问题 - 一旦商店更新,组件不会重新渲染。我在这里创建了另一个问题,如果你想看看http://stackoverflow.com/questions/40702409/react-mobx-component-not-updating-after-store-change。我觉得我疯了。 – Chris

0

如@Sulthan提到的,需要有由另一功能onClick={()=>store.changeMe()}包裹方法。 第二个问题是你缺少action装饰器的更新值的方法。 Mobx以每种方法更新属性的方式工作,它需要由@action进行修饰。因此,下面将解决问题import {action} from 'mobx,

@action change_me(){ 
    this.me = 'test 1'; 
}