在React组件unmounted之后setState的报错处理

最近在做项目的时候遇到一个问题,在 react 组件 unmounted 之后 setState 会报错。我们先来看个例子, 重现一下问题:

class Welcome extends Component {
  state = {
    name: ''
  }
  componentWillMount() {
    setTimeout(() => {
      this.setState({
        name: 'Victor Wang'
      })
    }, 1000)
  }

  render() {
    return <span>Welcome! {this.state.name}</span>
  }
}

class WelcomeWrapper extends Component {
  state = {
    isShowed: true
  }
  componentWillMount() {
    setTimeout(()=> {
      this.setState({
        isShowed: false
      })
    }, 300)
  }

  render() {
    const message = this.state.isShowed ? <Welcome /> : 'Bye!'
    return (
      <div>
         <span>{ message }</span>
      </div>
    )
  }
}

举的例子不是很好,主要是为了说明问题。在 WelcomeWrapper 组件中, 300ms 之后移除了 Welcome 组件,但在 Welcome 组件里 1000ms 之后会改变 Welcome 组件的状态。这时候 React 会报出如下错误:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.

这种错误情况一般出现在 react 组件已经从 DOM 中移除。我们在 react 组件中发送一些异步请求的时候, 就有可能会出现这样的问题。举个例子,我们在 componentWillMount 中发送异步请求,当请求成功返回数据,我们调用 setState 改变组件的状态。但是当请求到达之前, 我们更换了页面或者移除了组件,就会报这个错误。这是因为虽然组件已经被移除,但是请求还在执行, 所以会报setState() on an unmounted component的错误。

决解问题

好了, 我们现在知道问题出现的原因, 我们该怎么解决这个问题?思路也很简单, 我们只要在 react 组件被移除之前终止 setState 操作就行了。回到之前的例子, 我们可以这样做:

componentWillMount() {
  // 我们把 setTimeout 保存在 timer 里
  this.timer = setTimeout(() => {
    this.setState({
      name: 'Victor Wang'
    })
  }, 1000)
}

// 在组件将要被移除的时候,清除 timer
componentWillUnmount() {
  clearTimeout(this.timer)
}

类似的在处理 ajax 请求的时候也是这个套路, 在 componentWillUnmount 方法中终止 ajax 请求即可,以 jquery 为例:

componentWillMount() {
  this.xhr = $.ajax({
    // 请求的细节
  })
}

componentWillUnmount() {
  this.xhr.abort()
}

在处理 fetch 请求的时候思路也是一样的, 但是处理起来就没有那么容易了。 因为 Promise 不能被取消, 至少从目前的规范来看是没有相应的 API 来取消 Promise chain 的。将来可能会实现相应的 API, 感兴趣的可以看看这里这里的讨论。

fecth 请求的处理

为了让 Promise 可以被取消,我们处理的思路是这样的,我们在我们的 Promise 外面再包裹一层 Promise 来保证我们的 Promise 可以被取消。下面看代码:

const makeCancelable = (promise) => {
  let hasCanceled_ = false;

  const wrappedPromise = new Promise((resolve, reject) => {
    promise.then((val) =>
      hasCanceled_ ? reject({isCanceled: true}) : resolve(val)
    );
    promise.catch((error) =>
      hasCanceled_ ? reject({isCanceled: true}) : reject(error)
    );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled_ = true;
    },
  };
};

这个 pattern 是由@istarkov提出来的。
上面用到 Promise 的相关知识, 不熟悉 Promise 的同学可以参考这里
现在我们就可以用 makeCancelable 来取消我们的 fetch 请求了。

componentWillMount() {
  // 为了简单和方便, 这里我用 setTimeout 来模仿一个需要很长时间的 fetch 请求
  const mimicFetch = (resolve, reject) => {
    setTimeout(() => {
      resolve('Victor Wang')
    }, 1000)
  }
  const promise = new Promise(mimicFetch)

  this.cancelable = makeCancelable(promise)
  this.cancelable.promise.then(name => {
    this.setState({
      name
    })
  }, (e) => {
    console.log(e)
  })
}

componentWillUnmount() {
  // 在这取消
  this.cancelable.cancel()
}

预防错误

为了避免这种错误的发生,我们有一个通用的 pattern 来处理这个问题。


componentWillMount () {
// add event listeners (Flux Store, WebSocket, document, etc.)
}


componentWillUnmount () {
// remove event listeners (Flux Store, WebSocket, document, etc.)
}

注:有什么不对的地方, 欢迎指正!

posted @ 2017-04-05 09:53  最骚的就是你  阅读(4583)  评论(0编辑  收藏  举报