我是 typescript 的新手,当我尝试在 typescript 中使用useEffect进行响应时出现错误,Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'.,任何人都可以帮我为什么我会收到此错误吗?在这里,我已经放置了我的代码,我们将不胜感激任何帮助,

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

最佳答案

useEffect(EffectCallback类型)的函数应返回void() => void | undefined

function useEffect(effect: EffectCallback, deps?: DependencyList): void;

type EffectCallback = () => (void | (() => void | undefined));
在您的情况下,您返回void => boolean:
// void => boolean
return () => (isMounted.current = false);
要对其进行修复,请将范围添加到清洁功能的语句中:
const useIsMounted = () => {
  const isMounted = React.useRef(false);
  React.useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);
  return isMounted;
};

09-19 16:42