2017-04-25 44 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() { 
    // ... 
    } 
} 
相关问题