在unMounted组件上触发了反应componentDidMount()

时间:2015-12-31 01:40:06

标签: reactjs setstate

componentDidMount上调用来自数据存储的承诺的简单反应组件正在发出警告:

  

警告:setState(...):只能更新已安装或安装的组件。这通常意味着您在已卸载的组件上调用了setState()。这是一个无操作。请检查LocationNameView组件的代码。

我抛出了一些调试console.log以查看this.isMounted()是否为真/假,而componentDidMount this.isMounted()内部将在第一次返回false,然后它将会返回真正。我不确定文档是否清晰或者componentDidMount的名称是否在这里偏离我的推理,但似乎只有在实际安装组件时才应调用此方法。

enter link description here

componentDidMount: function() {

  var self = this;
  // make the request to the backend and replace the loading location text
  Models.Location.find(this.props.location)
    .then(function(location) {

        console.log(self.isMounted()); // <--- shows false then true 

        self.setState({ location : location });

    });

},

1 个答案:

答案 0 :(得分:4)

构建基础DOM表示时调用

componentDidMount,但尚未挂载到实际DOM。

显示有关在unMounted组件上设置状态的警告的原因是因为上面示例中的aSync回调可以在组件实际挂载到客户端/浏览器中的DOM树之前返回。

此处的教训是,如果您使用的是在componentWillMountcomponentDidMount的组件中设置状态的aSync回调,请先进行安全捕捉isMounted(),然后再继续设置州,即:

componentDidMount() {

  let self = this;

  PromiseMethod().then(function aSyncCallback(data) {

    if ( self.isMounted() ) {

      self.setState({...data});

    }

  });

}

React Component Lifecycle reference

相关问题