类型错误:func.apply 不是函数

2024-03-18

我正在尝试使用 useEffect 函数,如下所示:

    const [data, setData] = useState({ courses: [] });
    
    useEffect(async () => {
        const result = await axios.get(
            "http://example.com/api/v1/categories/"
        );
    
        await setData(result.data);
    }, []);
    
    console.log(data);

return (
    <div>
        <div>{data.info1}</div>
        <div>{data.info2}</div>
        <div>{data.info3}</div>
        <div>{data.info4}</div>
    </div>
);

但是当我尝试使用data变量有时会引发此错误:

TypeError: func.apply is not a function
HTMLUnknownElement.callCallback
C:/asdasd/node_modules/react-dom/cjs/react-dom.development.js:188
  185 |     window.event = windowEvent;
  186 |   }
  187 | 
> 188 |   func.apply(context, funcArgs);
      | ^  189 |   didError = false;
  190 | } // Create a global error event handler. We use this to capture the value
  191 | // that was thrown. It's possible that this error handler will fire more

我不知道,我想念哪里。


You 只能将普通函数作为参数传递给 useEffect,而不是异步函数。为了在 useEffect 中使用 async wait,您可以将函数编写为 IIFE(立即调用函数表达式 - 您编写函数并立即调用它)。

const [data, setData] = useState({ courses: [] });
    
useEffect(() => {
    (async () => {
        const result = await axios.get(
            "http://example.com/api/v1/categories/"
        );
        setData(result.data);
    })();
}, []);
    
console.log(data);

return (
    <div>
        <div>{data.info1}</div>
        <div>{data.info2}</div>
        <div>{data.info3}</div>
        <div>{data.info4}</div>
    </div>
);

或者您可以创建一个普通的命名异步函数,然后按如下方式调用它,

const [data, setData] = useState({ courses: [] });
    
useEffect(() => {
    const getResult = async () => {
        const result = await axios.get(
            "http://example.com/api/v1/categories/"
        );
        setData(result.data);
    };

    getResult();
}, []);

.
.
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类型错误:func.apply 不是函数 的相关文章