Home >Web Front-end >JS Tutorial >How to Fix 'Can't perform a React state update on an unmounted component' Errors?
Identifying the Problematic Component
The stack trace provided in the browser console indicates the component responsible for the state update violation. Each line in the stack trace represents a function call, with the component name or class constructor mentioned in the brackets:
This suggests that the TextLayer component is attempting to update its state after it has been unmounted.
Resolving the State Update Error
To fix the issue, you should verify that all async operations are cancelled or completed before the component unmounts in componentWillUnmount. In your case, this involves handling the throttleable function setDivSizeThrottleable.
Revised Code
In the revised Book component, you've made the following changes:
class Book extends React.Component { setDivSizeThrottleable: ((() => void) & Cancelable) | undefined; ... componentDidMount = () => { this.setDivSizeThrottleable = throttle( () => { this.setState({ pdfWidth: this.pdfWrapper!.getBoundingClientRect().width - 5, }); }, 500, ); this.setDivSizeThrottleable(); window.addEventListener("resize", this.setDivSizeThrottleable); }; componentWillUnmount = () => { window.removeEventListener("resize", this.setDivSizeThrottleable!); this.setDivSizeThrottleable!.cancel(); this.setDivSizeThrottleable = undefined; };
By properly handling the cancellation of the throttleable function, you can prevent the state update violation and resolve the "Can't perform a React state update on an unmounted component" error.
The above is the detailed content of How to Fix 'Can't perform a React state update on an unmounted component' Errors?. For more information, please follow other related articles on the PHP Chinese website!