2016-11-20 153 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'; 
}