2017-04-25 48 views
2
取消mobx自動運行功能

我在componentDidMount以下運行功能:上componentWillUnmount

componentDidMount() { 
     this.autoUpdate = autorun(() => { 
      this.setState({ 
       rows: generateRows(this.props.data) 
      }) 
     }) 
    } 

問題是另一個組件改變this.props.data當組件未安裝 - 爲此和我得到的。未裝入組件上的.setState警告。

所以我想刪除組件卸載後的自動運行。

我試着這樣做:

componentWillUnmount() { 
    this.autoUpdate = null 
} 

但自動運行功能仍然會觸發。一旦組件未被安裝,是否有辦法取消mobx autorun?

回答

3

autorun返回您需要調用的disposer函數以取消它。

class ExampleComponent extends Component { 
    componentDidMount() { 
    this.autoUpdateDisposer = autorun(() => { 
     this.setState({ 
     rows: generateRows(this.props.data) 
     }); 
    }); 
    } 

    componentWillUnmount() { 
    this.autoUpdateDisposer(); 
    } 

    render() { 
    // ... 
    } 
} 
相關問題