React成长路之踩坑路 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the xxx component.
意思是我们对一个未组装的组建进行了setState()的操作,这种情况会出现在callback
中,我们的异步请求返回数据之前,组件可能就已经被卸载了,等数据回来再使用setState
就会报出上面的警告,所以我们应该手动在componentWillUnmount时设置组件已卸载的标志,在数据处理setState()时先判断组件是否仍被挂载,否则不再执行setState
解决办法
componentDidMount() { this._isMounted = true //设置组件是否被装载标志位 this.getList() } componentWillUnmount() { this._isMounted = false } getList() { const user = this.props.user const result = getOrderListData(user) result.then(res => { return res.json() }).then(json => { if(this._isMounted) { //在setState()之前先判断组件是否被装载 this.setState({ lists: json }) } }).catch(ex => { if(_DEV_) { console.log('请求订单列表时报错报错' + ex.message) } }) }
码农随笔防失忆,只为记录风雨路上的脚丫印印~