简体   繁体   中英

React component state memory leak

The state in my React component does not get garbage collected when the component is dismounted, causing memory leak. I am using react@15.5.4 on Chrome 10.12.5 on macOS Sierra.

I am setting a state in componentDidMount like this .

To confirm the memory leak, I have added the following to my componentDidMount :

let arr = new Uint8Array(1024 * 1024 * 30);
this.setState({
  test: arr
});

and took a heap snapshot to confirm 30MB of Uint8Array allocated on heap.

Then, I have confirmed that the component gets dismounted by console.log in componentWillUnmount .

When I take a heap snapshot afterwards, even after allowing ample time for garbage collection to happen, Uint8Array remains in the heap.

Any ideas about where to start debugging this issue? Or any observation from the source code?

In my understanding you are expecting that componentWillUnmount works as a class destructor, but I think that React component lifecycle works in a different manner.

Object's properties like the state are commonly inited in the class constructor, then componentWillMount / componentDidMount and componentWillUnmount simply works with the same object.

If the component is not in the DOM anymore does not mean it's garbage collected. The same object will be used when (if) you re-mount it.

You can probably empty clean state yourself in componentWillUnmount if it make any sense for you. In this case I think GC will recover the memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM