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

在redux-saga的generator内通过map调用另一generator不触发如何解决

问题解决方案

根因分析

  • 你在Array.map中传入的generator函数不会被自动执行,map仅会返回一组未被迭代的generator实例。saga的call effect必须被saga执行器调度才能生效,未被迭代的generator内的effect自然不会触发。
  • 你没有对map返回的执行计划做任何调度处理,相当于只是生成了调用声明,没有实际触发执行。

修复方案

方案1:并行执行所有getdata调用

如果需要同时发起所有请求,使用saga提供的all effect包裹map生成的call数组即可:

import { call, all } from 'redux-saga/effects'

function* getdata(action) { 
  try {
    let response = yield call(doCall, {
      url: 'https://.....',
      method: 'GET', // 注意字符串类型的请求方法要加引号
    });
  } catch(e){
    console.error('请求出错', e)
  }
} 
function* updateData(action) { 
  try {
    let array = ['1', '2', '3'];
    // 调度所有call effect并行执行
    yield all(array.map(i => call(getdata, { ...action })))
  } catch(e){
    console.error('批量处理出错', e)
  }
}

方案2:串行依次执行getdata调用

如果需要按数组顺序逐个发起请求,使用for of循环逐个yield即可:

import { call } from 'redux-saga/effects'

function* updateData(action) { 
  try {
    let array = ['1', '2', '3'];
    // 按顺序逐个调度执行
    for (const i of array) {
      yield call(getdata, { ...action })
    }
  } catch(e){
    console.error('批量处理出错', e)
  }
}

注意事项

  • 不要在map/forEach这类普通数组迭代方法中直接定义generator函数,这类原生方法不会处理generator的迭代逻辑
  • 原代码中的GET请求方法如果是字符串常量,需要补充引号避免变量未定义报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:27:03