0
votes

I get the following error: "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."

And my useEffect hook looks like this using axios:

const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
    getSomething(new URLSearchParams(props.location.search), cancelToken).then((response: any) => {
      const res = response.data;
      if(isMounted.current) setState(res);
    });
    return () => {
      isMounted.current = false;
      if(!isMounted.current) cancelToken.cancel();
    }
  }, [props.location.search]);

Where do I have a memory leak? I am able to render my component without the axios return statement, but I still get the memory leak warning.

1
I am unsure why your approach isn't working, but sometimes I have had to resort to using something like the hook described here: gist.github.com/jaydenseric/… You would then check if isMounted is true before calling setState - sunero4
Where is this hook located exactly? - Alexander Staroselsky
This code doesn't represent the problem, please make a reproducible example How to create a Minimal, Reproducible Example - Dennis Vash
Edited using "useRef" - newbie

1 Answers

0
votes

Json fetching example using axios wrapper (Live Demo)

import React, { useState } from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";

export default function TestComponent(props) {
  const [text, setText] = useState("");

  useAsyncEffect(
    function* () {
      setText("fetching...");
      const response = yield cpAxios(props.url); // cancellable request
      setText(`Success: ${JSON.stringify(response.data)}`);
    },
    [props.url]
  );

  return <div>{text}</div>;
}