如何在NgRx Effect前后调用Reducer并消除ESLint警告
修复ESLint禁止在Effect中调用store.dispatch的问题
ESLint的这条规则是为了遵循NgRx的设计原则:Effect应该通过返回Observable
针对你的业务逻辑(锁定数据→更新后端→解锁数据),正确的实现方式是把所有需要触发的action都作为Effect返回流的一部分,让Store自动dispatch:
修正后的代码示例
this.actions$.pipe( ofType(actions.update), switchMap(action => { return this.backendService.update$(action.data).pipe( // 更新成功时发出成功action map(updatedResult => actions.updateSuccess(updatedResult)), // 更新失败时发出失败action(避免流中断) catchError(error => of(actions.updateFailure({ error, id: action.data.id }))), // 流启动时先发出锁定数据的action startWith(actions.lockData(action.data.id)), // 流结束时(无论成功/失败)发出解锁数据的action endWith(actions.unlockData(action.data.id)) ); }) );
关键改动说明
- 移除了所有
this.store.dispatch()调用,改为通过startWith、map、catchError、endWith将action注入到Effect的返回流中,Store会自动处理这些action的dispatch startWith(actions.lockData(...)):在执行后端请求前,先触发锁定数据的actionendWith(actions.unlockData(...)):不管后端请求成功还是失败,流结束时都会触发解锁数据的action,确保锁定状态一定会被清除- 保留了后端请求的成功/失败处理,将结果转换为对应的action,让Reducer处理状态更新
这种写法既满足了业务逻辑需求,又遵守了ESLint规则,同时符合NgRx的最佳实践。
内容的提问来源于stack exchange,提问作者Chriss
相关产品推荐
相关产品推荐

