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

React Native Keychain登录按钮onPress异步函数报错求助

问题解决:Promise-returning function provided to attribute where a void return was expected

错误原因

你定义的login是异步函数,异步函数默认会返回一个Promise。而按钮的onPress属性要求绑定的函数是**无返回值(void)**的,当你使用() => login()时,这个箭头函数会把login()返回的Promise作为自身返回值,类型不匹配就触发了该错误。

解决方案

有几种简单的修复方式:

方案1:用花括号包裹调用,不返回Promise

修改onPress的箭头函数,用花括号包裹执行逻辑,避免返回Promise:

<Button
  disabled={firstName === "" || lastName === "" || email === ""}
  type="filled"
  size="large"
  text="Log in"
  style={{ width: 160, height: 48, margin: 24 }}
  onPress={() => { login(); }}
/>

方案2:用void关键字忽略返回值

直接用void强制把Promise转为void,写法更简洁:

<Button
  disabled={firstName === "" || lastName === "" || email === ""}
  type="filled"
  size="large"
  text="Log in"
  style={{ width: 160, height: 48, margin: 24 }}
  onPress={() => void login()}
/>

方案3:额外捕获未处理的Promise拒绝(推荐)

虽然你的login函数里捕获了Keychain的错误,但如果后续的navigation.navigate抛出错误(比如路由名错误),会导致未处理的Promise拒绝。可以在调用时额外捕获:

<Button
  disabled={firstName === "" || lastName === "" || email === ""}
  type="filled"
  size="large"
  text="Log in"
  style={{ width: 160, height: 48, margin: 24 }}
  onPress={() => {
    login().catch(err => console.error("Login failed unexpectedly:", err));
  }}
/>

补充说明

异步函数的Promise返回特性是JavaScript的默认行为,只要用async声明,函数就必然返回Promise。核心解决思路就是让onPress绑定的函数不把这个Promise暴露出去,上面的几种方法都能实现这个目的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:22:50