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
中取消所有的订阅以及异步执行即可。
下面是代码1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46import 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 https://fb.me/react-unsafe-component-lifecycles for details.
解决方案
在 react 16.8 之后的版本中,修改了一下生命周期,移除了一些方法,componentWillMount
就是其中一个。现在如果要使用这个,使用 UNSAFE_componentWillMount
替换。但是不建议使用这个方法