Skip to content

abort() works, but still get "Warning: Can't perform a React state update on an unmounted component". CodeSandbox provided #207

Closed
@nth-chile

Description

@nth-chile

When returning abort as the useEffect cleanup function, the request aborts and the promise resolves as expected, but I still see the React warning: 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 a useEffect cleanup function. in Test (at App.js:15)

Question: How do I cancel a fetch on unmount (and not receive the React warning)?

In case this Codesandbox link expires, I'll paste the code below. I tried to keep it simple -- one component unmounts another component before its fetch finishes

App.js - unmount <Test /> after 100ms (to interrupt the API call made by <Test />)

import Test from "./Test";
import "./styles.css";

export default function App() {
  const [bool, setBool] = useState(true);

  // 100ms after mounting, set bool to false
  useEffect(() => {
    setTimeout(() => {
      setBool(false);
    }, 100);
  }, []);

  return <div className="App">{bool && <Test />}</div>;
}

Test.js - Make an API call using useFetch, and return abort from useEffect

import useFetch from "use-http";

export default function Test() {
  const { get, abort } = useFetch(
    "https://jsonplaceholder.typicode.com/posts/1"
  );

  const loadIt = async () => await get();

  useEffect(() => {
    loadIt();

    return abort;
  }, []);

  return <h1>I am here</h1>;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions