首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >对已卸载的组件执行React - setState()

对已卸载的组件执行React - setState()
EN

Stack Overflow用户
提问于 2015-10-02 16:09:14
回答 7查看 97.9K关注 0票数 96

在我的react组件中,当ajax请求正在进行时,im尝试实现一个简单的微调器- im使用state来存储加载状态。

出于某种原因,我的React组件中的下面这段代码抛出了这个错误

只能更新已挂载或正在挂载的组件。这通常意味着您在未挂载的组件上调用setState()。这是个禁区。请检查未定义组件的代码。

如果我去掉了第一个setState调用,错误就会消失。

代码语言:javascript
复制
constructor(props) {
  super(props);
  this.loadSearches = this.loadSearches.bind(this);

  this.state = {
    loading: false
  }
}

loadSearches() {

  this.setState({
    loading: true,
    searches: []
  });

  console.log('Loading Searches..');

  $.ajax({
    url: this.props.source + '?projectId=' + this.props.projectId,
    dataType: 'json',
    crossDomain: true,
    success: function(data) {
      this.setState({
        loading: false
      });
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(this.props.url, status, err.toString());
      this.setState({
        loading: false
      });
    }.bind(this)
  });
}

componentDidMount() {
  setInterval(this.loadSearches, this.props.pollInterval);
}

render() {

    let searches = this.state.searches || [];


    return (<div>
          <Table striped bordered condensed hover>
          <thead>
            <tr>
              <th>Name</th>
              <th>Submit Date</th>
              <th>Dataset &amp; Datatype</th>
              <th>Results</th>
              <th>Last Downloaded</th>
            </tr>
          </thead>
          {
          searches.map(function(search) {

                let createdDate = moment(search.createdDate, 'X').format("YYYY-MM-DD");
                let downloadedDate = moment(search.downloadedDate, 'X').format("YYYY-MM-DD");
                let records = 0;
                let status = search.status ? search.status.toLowerCase() : ''

                return (
                <tbody key={search.id}>
                  <tr>
                    <td>{search.name}</td>
                    <td>{createdDate}</td>
                    <td>{search.dataset}</td>
                    <td>{records}</td>
                    <td>{downloadedDate}</td>
                  </tr>
                </tbody>
              );
          }
          </Table >
          </div>
      );
  }

问题是,当组件应该已经被挂载(因为它是从componentDidMount调用的)时,我为什么会收到这个错误?我认为组件挂载后设置状态是安全的?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32903001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档