无法使用NGXS修补存储的更新状态。我一直看到类型错误:无法冻结

2022-06-27 00:00:00 state javascript angular ngxs angular11

我正在使用一个基本的角度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对象存储在状态中。

相关文章