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

ESLint报错:预期返回void却传入返回Promise的函数(React Hook Form)

解决React Hook Form异步onSubmit的ESLint报错问题

问题原因

form元素的onSubmit属性要求回调函数返回void,但handleSubmit接收异步函数后会返回一个Promise,触发ESLint的"Promise-returning function provided to attribute where a void return was expected"报错。你之前的空函数包裹失效,是因为只调用了handleSubmit(onSubmit)但没有执行它返回的实际提交处理函数。

解决方案

方案1:用void忽略Promise返回值

直接在onSubmit属性中调用handleSubmit返回的函数,通过void将返回值转为void,满足ESLint要求:

<form onSubmit={() => void handleSubmit(onSubmit)()}>

方案2:给异步函数添加错误捕获并声明返回类型

修改onSubmit函数,添加错误捕获逻辑,并显式声明返回Promise<void>,让ESLint识别为符合要求:

const onSubmit = async (values: IProductType): Promise<void> => {
  try {
    const response = await dispatch(createProductType({
      productType: values,
      shopId: shopId as string
    }));
    const newCreatedProductType = response.payload as IProductType;

    if (response.meta.requestStatus === requestStatusSuccess) {
      dispatch(getMessageAction(t('createSuccess', { ns: 'productType', name: values.name }), 'success'));
      dispatch(addProductType(newCreatedProductType));

      if (onCreateSuccess) {
          onCreateSuccess(newCreatedProductType);
      }

      reset();
    }
  } catch (error) {
    // 可选:添加错误提示逻辑
    dispatch(getMessageAction(t('createFailed', { ns: 'productType' }), 'error'));
  }
};

此时直接使用handleSubmit即可:

<form onSubmit={handleSubmit(onSubmit)}>

方案3:临时禁用ESLint规则(不推荐)

如果只是快速消除报错,可在代码行上方添加注释禁用对应规则,但这是治标不治本的方法:

// eslint-disable-next-line @typescript-eslint/no-misused-promises
<form onSubmit={handleSubmit(onSubmit)}>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 08:20:53