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

如何在类方法中使用saga effects,解决yield put执行失败问题

类方法中使用redux-saga effects执行异常的解决方案

问题原因

  • redux-saga的put等effect是纯描述对象,本身不执行实际操作,只有saga运行时环境能识别处理,手动调用生成器next()只会返回这个描述对象,不会触发dispatch动作。你之前的yield console.log能执行是因为console.log是在生成yield后面的表达式时就直接执行了,不是saga处理的结果。
  • 当前迭代逻辑存在两处错误:一是遍历逻辑写在了test生成器外部,不在saga运行时的执行上下文中;二是每次调用_process()都会生成新的生成器实例,单次next()调用最多只能执行到第一个yield,无法完成整个生成器的迭代。

解决方案

把处理器的执行逻辑放到saga内部,交由saga运行时接管生成器的迭代和effect处理,两种常用写法:

1. 串行执行所有处理器

export function* test(): Generator<any, any, any> {
  const processors: Processor[] = [];
  processors.push(new OrignalMembersOrder());
  // 继续添加其他处理器实例
  // processors.push(new OtherOrder());

  // 遍历执行所有处理器的_process方法,yield* 会委托saga处理内部所有yield的effect
  for (const processor of processors) {
    yield* processor._process();
  }
}

2. 并行执行所有处理器

如果需要多个处理器同时执行,可以使用saga的all effect:

import { all } from 'redux-saga/effects';

export function* test(): Generator<any, any, any> {
  const processors: Processor[] = [];
  processors.push(new OrignalMembersOrder());
  // 继续添加其他处理器实例
  // processors.push(new OtherOrder());

  // 并行执行所有处理器的_process
  yield all(processors.map(processor => processor._process()));
}

注意事项

test saga需要正常注册到redux-saga中间件中启动,比如在root saga中通过yield fork(test)或者其他事件监听方式启动,不要手动调用生成器的next方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:45:05