Home >Web Front-end >JS Tutorial >How to Fix 'Can't perform a React state update on an unmounted component' Errors?

How to Fix 'Can't perform a React state update on an unmounted component' Errors?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 08:51:15887browse

How to Fix

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:

  • in TextLayerInternal (created by Context.Consumer)
  • in TextLayer (created by PageInternal)

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:

  • Converted setDivSizeThrottleable to a cancelable function using throttle.cancel().
  • Added a cleanup function in componentWillUnmount to cancel the throttleable function.
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn