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

如何修复Angular NgRx中'Observable<never>'不可分配给'never'类型错误

报错原因

该报错是NgRx Effect的默认配置与你当前代码逻辑不匹配导致的:
createEffect 默认要求回调返回的Observable必须派发一个新Action,而你当前的Effect仅通过tap执行了存储token、页面跳转的副作用,没有返回任何Action,TypeScript推导返回的Observable类型为Observable<never>,与要求返回Action的类型规则冲突,因此抛出报错。

解决方法

分两种场景处理:

场景1:该Effect不需要派发新Action(适配你当前的业务逻辑)

在createEffect的第二个参数传入配置{ dispatch: false },显式告知NgRx该Effect不需要返回新Action,即可关闭对应的类型校验:

// auth.effects.ts 修改后代码
effectLogInSuccess$ = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActionTypes.LOGIN_SUCCESS),
      tap((user) => {
        localStorage.setItem('token', user.payload.token);
        this.router.navigateByUrl('/');
      })
    ),
    { dispatch: false } // 新增配置
);

场景2:该Effect执行完需要派发新Action

如果你需要在登录成功后触发其他业务逻辑,可在管道末尾通过map返回对应的Action即可:

effectLogInSuccess$ = createEffect(() =>
    this.actions$.pipe(
      ofType(AuthActionTypes.LOGIN_SUCCESS),
      tap((user) => {
        localStorage.setItem('token', user.payload.token);
        this.router.navigateByUrl('/');
      }),
      // 返回你要派发的新Action
      map(() => yourNextAction())
    )
);
额外类型优化建议

你当前的Action参数用了props<any>,可以替换为明确的类型定义,避免后续类型隐患:

// auth.actions.ts 修改后代码
interface LoginSuccessPayload {
  payload: {
    token: string;
    // 补充其他你需要的字段
  }
}

export const actionLogInSuccess = createAction(
  AuthActionTypes.LOGIN_SUCCESS,
  props<LoginSuccessPayload>()
);
报错截图

报错截图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 19:54:03