You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在useEffect中使用async/await时,如何处理@typescript-eslint/no-floating-promises?

React项目中ESLint浮动Promise错误的疑问

我有一个基于TypeScript和ESLint的小型React项目,页面加载时通过useEffect发起fetch请求填充表格数据。请求本身能正常执行,但ESLint在调用fetchSsidWhitelist()的位置抛出错误:

"Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the void operator. (eslint@typescript-eslint/no-floating-promises)"

我知道可以用void关键字或者Promise链式调用(如下方两个选项)消除错误,但不理解为什么必须这么做。另外,如果必须处理未捕获的Promise且要使用.catch,能不能只使用async/await语法,不混合链式调用?

ESLint错误示例代码

useEffect(() => {
    const fetchSsidWhitelist = async () => {
        try {
            const response = await fetch('/Admin/whitelisting/ssid-whitelist');

            if (!response.ok) {
                setShowErrorMessage(true);
                throw new Error(await response.text());
            }

            const data: SsidWhitelist[] = (await response.json()) as SsidWhitelist[];

            setResults(data);
        } catch (error) {
            console.log('An error occurred during the fetch: ', error);
        }
    };

    fetchSsidWhitelist()
}, []);

选项1:通过Promise链式调用添加catch

fetchSsidWhitelist()
    .catch((error) => console.log(error));

选项2:使用void标记忽略Promise

void fetchSsidWhitelist()

更新:我采纳了@Jahedule Hoque的建议,将data变量类型改为SsidWhitelist[](之前错误设为Promise类型),但仍未解决原有的浮动Promise错误。

内容的提问来源于stack exchange,提问作者Matt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:06:09