react项目报错集锦

2,056 阅读1分钟

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.

错误截图

解决方案

解决方法上面其实以及说到了。只需要找到对象的文件,在 componentWillUnmount 中取消所有的订阅以及异步执行即可。

下面是代码

import React, { Component } from 'react'
import Avatar from '@img/common/avatar.jpeg'
import Stance from '@img/common/stance.png'

class CusImage extends Component {  
  constructor(props){
    super(props)

    const defaultImage = props.isAvatar ? Avatar : Stance
    
    this.state = {
      src: defaultImage
    }
  }
  
  componentDidMount(){
    const THIS = this
    const {imgSrc} = this.props
    const img = new Image()
    img.src = imgSrc
    img.onload = function(){
      THIS.setState({
        src: imgSrc
      })
    }
  }

  // 添加以下代码
  componentWillUnmount(){
    // 如果有定时器需要清除
    // clearTimeout(this.timer)
    this.setState = (state, callback) => {
      return
    }
  }
  
  render (){
    const {src} = this.state
    const {className, alt = "cus-img"} = this.props
    return (
      <img className={className} src={src} alt={alt}/>
    )
  }
}

export default CusImage

react-dom.development.js:12427 Warning: componentWillMount has been renamed, and is not recommended for use. See fb.me/react-unsaf… for details.

错误截图

解决方案

在 react 16.8 之后的版本中,修改了一下生命周期,移除了一些方法,componentWillMount就是其中一个。现在如果要使用这个,使用 UNSAFE_componentWillMount 替换。但是不建议使用这个方法