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

React Native中解决Generator函数map内yield关键字报错问题

解决Generator函数中yield在map回调里的语法错误问题

你遇到的SyntaxError: yield is a reserve word错误,核心原因是**yield关键字只能直接在Generator函数的顶层作用域或者嵌套的Generator/async函数中使用**,而你把它放在了map的箭头回调函数(这是一个普通函数)里,JavaScript引擎不允许这种用法。

最直接的修复方案:直接调用同步函数

先看你的formatArrayToCamelCase函数,它是纯同步的格式转换函数,没有任何异步操作,完全不需要用Redux Saga的yield call()来调用。直接执行函数就能得到结果:

export function* fetchWeighInWeighOutEvent(action: FetchWeighInWeighOutEventAction): any {
  ...
  Object.values(locations).map((location) => {
    let timeslotsArray = location.timeslots;
    if (timeslotsArray.length > 0) {
      // 直接调用同步转换函数,无需yield call
      let camelCaseTimeslots = formatArrayToCamelCase(timeslotsArray);
      // 这里可以继续处理转换后的驼峰格式数组
    }
  });
  ...
}

若未来需要处理异步转换的情况

假设以后你的格式转换逻辑变成了异步操作(比如需要调用API获取转换规则),那不能再用map,得改用for...of循环,这样就能在循环内部直接使用yield:

export function* fetchWeighInWeighOutEvent(action: FetchWeighInWeighOutEventAction): any {
  ...
  // 用for...of替代map,让yield处于Generator函数的直接作用域内
  for (const location of Object.values(locations)) {
    let timeslotsArray = location.timeslots;
    if (timeslotsArray.length > 0) {
      // 此时yield语法合法,可正常调用异步操作
      let camelCaseTimeslots = yield call(formatArrayToCamelCase, timeslotsArray);
      // 处理异步返回的转换结果
    }
  }
  ...
}

补充说明

Redux Saga的call函数主要用来包装异步操作(比如Promise、async函数),让Saga能够暂停Generator函数直到异步操作完成。对于纯同步的函数调用,直接执行即可,不需要额外的Saga effects。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:46:51