react警告:Can only update a mounted or mounting component. This usually means

523 阅读1分钟

报这个错归根到底的原因是:试图在页面卸载后操作页面元素,比如以下几种实例:

1.window的几个事件。例如onscroll、ontouchmove等,在某一个页面绑定了事件函数fun,但是当此页面卸载时,事件函数fun还存在,可能fun试图操作被卸载组件的某个元素,因此报错。 解决方式: 在componentWillUnmount函数中,取消掉事件绑定,以onscroll事件为例:

componentWillUnmount(){
    window.onscroll = null
}

2.设置了定时器,在页面卸载后,定时器还在操作页面里的元素,例如以下是我编写的一个toast组件:

import React, { Component } from 'react';
import '../styles/Toast.css';
class Toast extends Component {
  constructor(props) {
    super(props);
    this.state = {
        isShow: false,
        tip: '不能为空!'
    };
  }
show = (tip, time = 2500, cb = () => {}) => {
    this.setState({
        isShow: true,
        tip
    })
    setTimeout(() => {
        this.setState({
            isShow: false
        })
        cb()
    }, time)
}
hide = () => {
    this.setState({
        isShow: false
    })
}
componentWillUnmount(){
    this.hide()
}
componentDidMount() {
}
  render() {
    const { isShow, tip } = this.state;
    const { locate } = this.props
    return (
      <div className={ `toast ${ isShow ? 'isShow' : 'hide' } ${ locate=='top' ? 'locateTop' : '' }` }>{tip}</div>
    );
  }
}
export default Toast;

//--------在别的组件调用-----------
//<Toast
//  ref={(e) => { e && (this.toast = e) }}
//  position={'center'}
//  show={show}
///>

当我在别的组件里调用:

this.toast.show('注册成功,立即去登录', 3000)//3000是弹出的时间长度

在此组件消失之前,我已经跳到别的页面,但是toast在3秒之后会执行消失操作,因为页面卸载,所以操作不到toast,就会报错。