2

Sometimes I get an error and the full error message is: "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."

What is the best way to fix this? This is my code:

const CustomRefresh = (props) => {
  const {
    isCurrent, isScheduled
  } = props;
  const [refreshing, setRefreshing] = useState(false);

  const inventoryContext = useContext(inventoryContext);

  const onRefresh = React.useCallback(async () => {
    setRefreshing(true);

    if (isCurrent) {
      await inventoryContext.refreshToday();
    }

    if (isScheduled) {
      await inventoryContext.refreshScheduled();
    }

    setRefreshing(false);
  }, [refreshing]);

  return (
    <CustomRefresh refreshing={refreshing} style={style} onRefresh={onRefresh}>
      {children}
    </CustomRefresh>
  );
};
zosozo
  • 393
  • 2
  • 5
  • 16

1 Answers1

3

Add a ref in which you track whether it is unmounted. Then in your function check that ref before setting asynchronously setting state:

  const unmounted = useRef(false);
  useEffect(() => {
    return () => { unmounted.current = true };
  }, []);

  const onRefresh = React.useCallback(async () => {
    setRefreshing(true);

    if (isCurrent) {
      await inventoryContext.refreshToday();
    }

    if (isScheduled) {
      await inventoryContext.refreshScheduled();
    }

    if (!unmounted.current) {
       setRefreshing(false);
    }
  }, [refreshing]);
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98