You need to enable JavaScript to run this app. NGXS派发GetUser Action时提示string无法赋值给{email:string}参数如何解决
优惠活动
大模型
产品
解决方案
定价
更多

NGXS派发GetUser Action时提示string无法赋值给{email:string}参数如何解决

问题根因

你定义的GetUser Action构造函数要求入参是包含email字段的对象类型{email: string},但你在调用时直接传入了字符串类型的userEmail,导致类型不匹配触发报错。除此之外你的状态处理逻辑还存在死循环隐患。

修复步骤

1. 修正组件中Action调用的传参格式

将组件getUser方法中dispatch的代码修改为传入符合类型要求的对象:

getUser() {
  let userEmail = localStorage.getItem('email') || '';
  // 原错误写法为 new GetUser(userEmail),修改为包裹成要求的对象结构
  this.store.dispatch(new GetUser({ email: userEmail })).subscribe((data) => {
    this.router.navigate(['/profile']);
  });
  this.userService.getUser(userEmail).subscribe((response) => (
    console.log(response)
  ));
}

2. 移除ProfileState中的死循环代码

你在GetUser的Action处理逻辑中,拿到接口返回结果后又调用了ctx.dispatch(new GetUser(this.profile)),会导致无限重复触发拉取用户接口,直接删除该行即可,同时可删除未使用的profile实例属性:

@Action(GetUser)
getUser(ctx: StateContext<ProfileStateModel>, action: GetUser ){
  const state = ctx.getState();
  return this.userService.getUser(action.payload.email).pipe(
    tap((profile) => {
      ctx.setState({
        ...state,
        userProfile:profile
      });
      // 删除下方这行死循环代码即可
      // ctx.dispatch(new GetUser(this.profile));
    })
  );
}

历史同类问题说明

之前你用userId传参时遇到的报错也是相同原因:Action构造函数要求传入{userId: number}类型的对象,你直接传了number类型的userId值,改为包裹成对象传入即可解决。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 03:45:03