Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
nth-chile opened this issue Mar 17, 2020 · 5 comments

Comments

@nth-chile
Copy link

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>;
}
@alex-cory
Copy link
Collaborator

It should abort already when unmounting. See this line. I will take a look at this asap

@nth-chile
Copy link
Author

I see, cool. abort does cancel the request, and any statements following the call to req.get() will run immediately after abort is called. Which kinda makes the React warning seem unwarranted ... or I don't have enough knowledge about unmounting/cleanup

@alex-cory
Copy link
Collaborator

I think I have a fix for this issue in this PR. I block all state from updating if the component is not mounted, so if it still happens I will be very confused.

@nth-chile
Copy link
Author

Awesome. I will check it out.

@alex-cory
Copy link
Collaborator

This should be fixed with v0.4.0. Let me know if the issue persists and I'll reopen this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants