Reactjs: Can't perform a React state update on an unmounted component

Reactjs 遇到的warning

下方报错信息是控制台打印出的警告信息,虽然不会影响功能的执行,但是看到有一片红色的报错,会很碍眼。

Warning: Can't perform a React state update 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.

问题主要是我们在与后端进行数据交互的时候,一般都是采用异步的方式去请求数据。当我们是用reactjs时,如果在componentWillMount或者在componentDidMount中进行请求时,在接口返回后我们使用setState({}),这种场景下就会出现这个上述的警告。

产生的原因是组件还未装载上就开始执行this.setState的操作了,参考官网,主要解决方法如下:

componentDidMount () {
        this.mounted = true
        this.setState({loading:true})
        baseAjax({
            url:Uri.GET_DISPLAY_TITLES,
            data:{}
        }).then((res)=>{
            if(this.mounted){
                this.setState({
                    checkedDisplayTitles:res.data.displayTitles,
                    loading:false
                })
            }
        })
    }

    componentWillUnmount() {
        this.mounted = false
    }

这样的话,上述警告就会消除了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值