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

返回Promise的async函数传入期望void的属性引发SonarCloud报错

解决SonarCloud的Promise返回值报错问题

错误原因

SonarCloud的这个报错是因为:你传递给onAuthMethodSelected的handleAuthorisationOnClick是async函数,这类函数会自动返回一个Promise,但React的事件回调(比如按钮的onClick)要求的是无返回值(void),两者不匹配所以触发了规则警告。

具体解决办法

方法1:去掉async(如果loginWithRedirect不需要异步等待)

如果loginWithRedirect是同步跳转逻辑(比如直接跳转到授权页,不需要等待异步结果),直接把async和返回类型Promise<void>去掉,让函数返回void:

const handleAuthorisationOnClick = (authMethod: string): void => {
  loginWithRedirect({
    connection: authMethod,
    // ...其他参数
  });
};

这是最直接的解决方式,完全符合事件回调的要求。

方法2:在调用处用void忽略Promise返回值

如果必须保留async(比如需要处理loginWithRedirect的异步错误),可以在调用handleAuthorisationOnClick的时候,用void关键字吃掉Promise返回值,让外层函数返回void:
修改AuthorisationModal里的按钮点击逻辑:

<Button
  onClick={() => void onAuthMethodSelected(connectionName)}
>
  {methods.label}
</Button>

或者在传递props的时候直接包装:

<AuthorisationModal
  onAuthMethodSelected={(authMethod) => void handleAuthorisationOnClick(authMethod)}
  // ...其他props
/>

方法3:内部处理Promise,让函数返回void

如果需要处理loginWithRedirect的异步结果(比如捕获错误),可以去掉async,直接用.catch处理Promise,不返回任何值:

const handleAuthorisationOnClick = (authMethod: string): void => {
  loginWithRedirect({
    connection: authMethod,
    // ...其他参数
  }).catch(error => {
    // 这里处理错误,比如打印日志或提示用户
    console.error('授权跳转失败:', error);
  });
};

这样函数本身返回void,既保留了错误处理,又符合SonarCloud的规则要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 20:35:22