无法使用NGXS修补存储的更新状态。我一直看到类型错误:无法冻结 [英] Unable to patch the state with update to the store using NGXS. I keep seeing type error: cannot freeze

查看:25
本文介绍了无法使用NGXS修补存储的更新状态。我一直看到类型错误:无法冻结的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个基本的角度11应用程序,它实现了身份验证(使用AWS Cognito&;Amplify)。我在这里想要做的很简单。我正在使用内置的AWS Amplify方法进行身份验证。我正在使用NGXS存储令牌、用户信息等与身份验证相关的项目。

import { State, Action, StateContext, Selector } from '@ngxs/store';
import { AuthStateModel, defaultAuthState } from './auth.model';
import {
  LoginAction,
  AuthenticationCheckAction,
  LogoutAction,
} from './auth.actions';
import { Auth } from 'aws-amplify';
import { environment } from 'src/environments/environment';
import { Injectable } from '@angular/core';
import { updateItem } from '@ngxs/store/operators';

@State<AuthStateModel>({
  name: 'authState',
  defaults: defaultAuthState,
})
@Injectable()
export class AuthState {
  cognitoClientId = environment.cognitoClientId;
  cognitoCallbackURL = environment.cognitoCallbackURL;
  cognitoDomainName = environment.cognitoDomainName;
  loginurl = `https://${this.cognitoDomainName}/login?response_type=code&client_id=${this.cognitoClientId}&redirect_uri=${this.cognitoCallbackURL}`;

  @Selector()
  static getIsLoggedIn(state: AuthStateModel) {
    console.log('from getIsLoggedIn selector =>', state);
    return state.isLoggedIn;
  }

  @Action(LoginAction)
  login() {
    window.location.assign(this.loginurl);
  }

  @Action(AuthenticationCheckAction)
  checkLogin({ getState, patchState }: StateContext<AuthStateModel>) {
    const state = getState();
    Auth.currentAuthenticatedUser()
      .then((currentUser) => {
        const isLoggedIn = true;
        const username = currentUser?.attributes?.name;
        patchState({
          currentUser,
          isLoggedIn,
          username,
        });
      })
      .catch((err) => console.log(err));
    return;
  }

  @Action(LogoutAction)
  logout({ patchState }: StateContext<AuthStateModel>) {
    Auth.signOut()
      .then((data) => {
        console.log(data);
        patchState(defaultAuthState);
      })
      .catch((err) => console.log(err));

    return;
  }
}

除了在check Login函数内遇到patchState方法外,一切都正常,它会在浏览器控制台中抛出以下错误。:-

TypeError: Cannot freeze
    at Function.freeze (<anonymous>)
    at deepFreeze (ngxs-store.js:1869)
    at ngxs-store.js:1884
    at Array.forEach (<anonymous>)
    at deepFreeze (ngxs-store.js:1874)
    at ngxs-store.js:1884
    at Array.forEach (<anonymous>)
    at deepFreeze (ngxs-store.js:1874)
    at ngxs-store.js:1884
    at Array.forEach (<anonymous>)
奇怪的是,如果我注释掉pathState()方法中提到的currentUser,错误就消失了。因此,更新状态中的对象是有问题的。

ngxs-store.js文件的此错误中引用的行包含以下代码。1869处的行是开头的对象冻结(O)行:-

const deepFreeze = (/**
 * @param {?} o
 * @return {?}
 */
(o) => {
    Object.freeze(o);
    /** @type {?} */
    const oIsFunction = typeof o === 'function';
    /** @type {?} */
    const hasOwnProp = Object.prototype.hasOwnProperty;
    Object.getOwnPropertyNames(o).forEach((/**
     * @param {?} prop
     * @return {?}
     */
    function (prop) {
        if (hasOwnProp.call(o, prop) &&
            (oIsFunction ? prop !== 'caller' && prop !== 'callee' && prop !== 'arguments' : true) &&
            o[prop] !== null &&
            (typeof o[prop] === 'object' || typeof o[prop] === 'function') &&
            !Object.isFrozen(o[prop])) {
            deepFreeze(o[prop]);
        }
    }));
    return o;
});

不够精明,无法理解这里发生的事情。这只是一个简单的修补国家的尝试。状态模型如下:-

export class AuthStateModel {
  isLoggedIn: Boolean;
  currentUser: Object;
  username: String;
}

export const defaultAuthState: AuthStateModel = {
  isLoggedIn: false,
  currentUser: {},
  username: '',
};

有什么我可以做的来让它正常工作吗?

推荐答案

有时,当我遇到这样的问题时,我无法更改对象,我只是克隆它。我通常使用lodash的cloneDeep来执行此操作:

patchState({
  currentUser: _.cloneDeep(currentUser),
  isLoggedIn,
  username,
});

此外,请尽量保持状态可序列化。不熟悉AWS Cognito&;Amplify,但如果CurrentUser是一个绑定了方法和其他成员的对象,以后需要它,那么我不会将CurrentUser对象存储在状态中。

这篇关于无法使用NGXS修补存储的更新状态。我一直看到类型错误:无法冻结的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆