簡體   English   中英

無法在卸載的組件上調用setState(或forceUpdate)

[英]Can't call setState (or forceUpdate) on an unmounted component

我試圖在組件更新后從服務器獲取數據,但我無法做到這一點。 據我了解componentWillUnmount當組件將被摧毀叫,但我從來沒有需要摧毀它,所以它是對我沒用。 這會是什么解決方案? 什么時候我應該設置狀態?

async componentDidUpdate(prevProps, prevState) {
  if (this.props.subject.length && prevProps.subject !== this.props.subject) {
    let result = await this.getGrades({
      student: this.props.id,
      subject: this.props.subject
    });
    this.setState({
      subject: this.props.subject,
      grades: result
    });
  }
}

async getGrades(params) {
  let response, body;

  if (params['subject'].length) {
    response = await fetch(apiRequestString.gradesBySubject(params));
    body = await response.json();
  } else {
    response = await fetch(apiRequestString.grades(params));
    body = await response.json();
  }

  if (response.status !== 200) throw Error(body.message);

  return body;
}

完整錯誤:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, 
but it indicates a memory leak in your application. To fix, cancel all subscriptions and
asynchronous tasks in the componentWillUnmount method.

我在這個例子中使用的一個常見模式是類似的

componentWillUnmount() {
    this.isCancelled = true;
}

然后在您正在等待解析異步函數的代碼中,您將在設置狀態之前添加一個檢查:

async componentDidUpdate(prevProps, prevState) {
    if (this.props.subject.length && prevProps.subject !== this.props.subject) {
        let result = await this.getGrades({
            student: this.props.id,
            subject: this.props.subject
        });
        !this.isCancelled && this.setState({
            subject: this.props.subject,
            grades: result
        });
    }
}

這將停止對已卸載/卸載組件的任何狀態設置

接受的答案有效,並且是在組件呈現方法(getInitialState,componentWillMount,componentDidMount)中調用異步函數的問題的有效解決方法。

但更好的做法是使用Redux和Flux等狀態管理助手以及全局存儲,這可以避免多個setStates的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM