React-未安装组件上的setState()

JavaScript

十三JimHarry

2020-03-12

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

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

只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了setState()。这是无人值守。请检查未定义组件的代码。

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

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调用了它),为什么我会收到此错误?我认为一旦安装了组件,就可以安全地设置状态了?

第1263篇《React-未安装组件上的setState()》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
阿飞神乐 2020.03.12

对于需要其他选择的用户,可以使用ref属性的回调方法。handleRef的参数是对div DOM元素的引用。

有关ref和DOM的详细信息:https : //facebook.github.io/react/docs/refs-and-the-dom.html

handleRef = (divElement) => {
 if(divElement){
  //set state here
 }
}

render(){
 return (
  <div ref={this.handleRef}>
  </div>
 )
}
Pro老丝 2020.03.12

问题是,当应该已经安装了组件时(为什么从componentDidMount调用了它),为什么我会收到此错误?我认为一旦安装了组件,就可以安全地设置状态了?

不是从调用的componentDidMount您会componentDidMount产生一个回调函数,该函数将在计时器处理程序的堆栈中执行,而不是在的堆栈中执行componentDidMount显然,this.loadSearches在执行回调()时,该组件已卸载。

因此,已接受的答案将保护您。如果您使用的其他异步API不允许您取消异步功能(已经提交给某些处理程序),则可以执行以下操作:

if (this.isMounted())
     this.setState(...

这将摆脱您在任何情况下报告但它确实感觉像地毯下扫的东西,特别是如果你的API提供了一个取消能力的错误信息(如setInterval用干clearInterval)。

null 2020.03.12

没有看到渲染功能有点困难。尽管已经可以发现您应该执行的操作,但是每次使用间隔时,都必须在卸载时清除它。所以:

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

componentWillUnmount () {
    this.loadInterval && clearInterval(this.loadInterval);
    this.loadInterval = false;
}

由于卸载后仍可能会调用成功和错误回调,因此可以使用interval变量检查其是否已安装。

this.loadInterval && this.setState({
    loading: false
});

希望这会有所帮助,如果这样做不起作用,请提供渲染功能。

干杯

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android