react runtime_error ai_generated true

Warning: useEffect must not return anything besides a function, which is used for clean-up. You returned: undefined.

ID: react/effect-cleanup-not-a-function

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2023-04-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
React 16.8+ active
React 17.0.2 active
React 18.2.0 active

Root Cause

The callback passed to useEffect returns a value that is not a function (e.g., undefined, null, an object, or a Promise), which violates the rule that the return value must be a cleanup function or nothing.

generic

中文

传递给 useEffect 的回调返回了一个非函数的值(例如 undefined、null、对象或 Promise),违反了返回值必须是清理函数或无返回值的规则。

Official Documentation

https://reactjs.org/docs/hooks-effect.html#effects-with-cleanup

Workarounds

  1. 95% success If you need async operations, define an async function inside the effect and call it immediately: useEffect(() => { const fetchData = async () => { ... }; fetchData(); }, []);
    If you need async operations, define an async function inside the effect and call it immediately: useEffect(() => { const fetchData = async () => { ... }; fetchData(); }, []);
  2. 90% success If you need a cleanup function, return a function explicitly: useEffect(() => { const subscription = source.subscribe(); return () => { subscription.unsubscribe(); }; }, []);
    If you need a cleanup function, return a function explicitly: useEffect(() => { const subscription = source.subscribe(); return () => { subscription.unsubscribe(); }; }, []);

中文步骤

  1. If you need async operations, define an async function inside the effect and call it immediately: useEffect(() => { const fetchData = async () => { ... }; fetchData(); }, []);
  2. If you need a cleanup function, return a function explicitly: useEffect(() => { const subscription = source.subscribe(); return () => { subscription.unsubscribe(); }; }, []);

Dead Ends

Common approaches that don't work:

  1. Adding an empty return statement (return;) 30% fail

    This is actually correct if the function returns nothing, but if the problem is an async function, adding return; doesn't fix the implicit Promise return.

  2. Wrapping the async code in a separate function and calling it 40% fail

    If the async function is still used as the effect callback, it still returns a Promise. The fix is to define async inside the effect, not as the effect itself.

  3. Using useEffect(async () => { ... }, []) 70% fail

    An async function always returns a Promise, which is not a valid cleanup function. React will fire this warning and the cleanup may not work.