NGRX Effects使用RxJS delay操作符导致动作执行顺序异常问题
问题分析与修复方案
核心代码错误
你的代码存在两处关键问题,直接导致了动作序列异常:
动作实例创建错误
在aEffects的aActionSuccessEffect$中,map操作返回的是动作创建函数bAction,而非调用它生成的动作实例bAction()。NGRX只能识别有效的动作对象,返回函数本身会导致调度逻辑异常,引发动作顺序混乱。语法错误
在bEffects的bActionEffect$中,map操作里的bActionSuccess()多了一个多余分号,且缺少闭合括号,这会导致代码编译异常或运行时逻辑错误。
修正后的代码
aEffects 修正版
@Injectable() export class aEffects { aActionEffect$ = createEffect(() => { return this.actions$.pipe( ofType(aAction), map(() => aActionSuccess()) ); }); aActionSuccessEffect$ = createEffect(() => { return this.actions$.pipe( ofType(aActionSuccess), delay(1000), map(() => bAction()) // 修正:调用动作创建函数生成实例 ); }); constructor(protected readonly actions$: Actions) {} }
bEffects 修正版
@Injectable() export class bEffects { bActionEffect$ = createEffect(() => { return this.actions$.pipe( ofType(bAction), switchMap(() => { return this.bService.doAsynchronousTask().pipe( map(() => bActionSuccess()) // 修正:移除多余分号,补全语法 ); }) ); }); constructor( protected readonly actions$: Actions, protected readonly bService: BService, ) {} }
修正后的执行逻辑
修正后,动作序列会符合你的预期:
- 触发
aAction aEffects调度aActionSuccess- 等待1秒(
delay(1000)生效) - 调度
bAction bEffects调用bService.doAsynchronousTask(),完成后调度bActionSuccess
同时请确保你的动作定义遵循NGRX标准格式,例如:
import { createAction } from '@ngrx/store'; export const aAction = createAction('[A] Action'); export const aActionSuccess = createAction('[A] Action Success'); export const bAction = createAction('[B] Action'); export const bActionSuccess = createAction('[B] Action Success');
内容的提问来源于stack exchange,提问作者Hadrien Thomas
相关产品推荐
相关产品推荐

