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

为什么await调用async声明的MicButton函数时返回值为undefined?

问题原因
  • 根本原因1:MicButton函数没有显式返回值,async函数执行完毕默认返回undefined。你写在Voice.onSpeechResults回调里的return属于回调函数自身的返回值,和外层的MicButton完全无关,无法被外层获取。
  • 根本原因2:onSpeechResults是异步事件监听,你调用Voice.start之后MicButton会立即执行结束,不会等待语音识别结果返回,await只能等待Promise状态变更,你当前的MicButton没有返回关联识别结果的Promise,自然拿不到后续返回的内容。
  • 额外问题:每次调用MicButton都会重复绑定onSpeechResults监听,多次调用会出现回调触发多次、内存泄漏的问题。
修复方案

修改MicButtons.js代码如下即可:

import Voice from 'react-native-voice'

export const MicButton = () => {
  // 返回Promise,等待识别结果后变更状态
  return new Promise((resolve, reject) => {
    // 先清空原有监听,避免重复触发
    Voice.removeAllListeners()

    // 绑定识别结果监听
    Voice.onSpeechResults = (res) => {
      const resultText = JSON.parse(JSON.stringify(res)).value[0]
      resolve(resultText)
      // 识别完成后停止识别、清理监听
      Voice.stop()
      Voice.removeAllListeners()
    }

    // 绑定错误监听,避免Promise永久pending
    Voice.onSpeechError = (err) => {
      reject(err)
      Voice.stop()
      Voice.removeAllListeners()
    }

    // 启动语音识别
    Voice.start('en-US').catch(reject)
  })
}

原有调用逻辑不需要修改,await MicButton()即可正常获取识别结果。

注意事项
  • 使用前确保已申请对应平台的麦克风、语音识别权限,否则会触发识别错误。
  • 可根据业务需求补充更多事件监听,适配识别结束、音量变化等场景的处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:54:01