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

AWS Amplify问题:无法访问用户对象中已存在的organizationId属性

问题描述

相关代码

src/index.js 中的 Amplify 初始化代码

import { Amplify } from 'aws-amplify';
import { BrowserRouter } from 'react-router-dom';

Amplify.configure({
  Auth: {
    userPoolId: process.env.REACT_APP_AWS_COGNITO_USER_POOL_ID,
    region: process.env.REACT_APP_AWS_COGNITO_REGION,
    userPoolWebClientId: process.env.REACT_APP_AWS_COGNITO_APP_CLIENT_ID,
    storage: browserStorage,
    authenticationFlowType: 'CUSTOM_AUTH', 
  },
});

src/app.jsx 中的代码

import { Auth } from 'aws-amplify';

const App = () => {
  const [currentUser, setCurrentUser] = useState('NotChecked');
  const [userGroups, setUserGroups] = useState(null);

  useEffect(() => {
    Auth.currentAuthenticatedUser()
      .then(function (result) {
        console.log('storage.organizationId: ', result.storage.organizationId);
        console.log(' == Auth.currentAuthenticatedUser() result: ', result);
        setCurrentUser(result);
        const groups =
          result.signInUserSession.accessToken.payload['cognito:groups'];
        setUserGroups(groups);
      })
      .catch(function (error) {
        console.error(error);
        setCurrentUser('NotSignedIn');
      });

问题现象

控制台日志显示 result.storage.organizationId 的值为 undefined,但展开打印的 result 对象时,storage 属性下确实存在 organizationId 键且对应值为整数。该 organizationId 是在 App 组件的孙子组件中设置到 localStorage 中的。


原因分析
  • 异步打印的时效性差异:console.log(result) 是异步展开的——当你在控制台点击展开对象时,浏览器会读取对象的当前状态,而非打印瞬间的状态。而 console.log('storage.organizationId: ', result.storage.organizationId) 是同步执行的,打印的是调用瞬间 organizationId 的值,此时孙子组件还未完成 organizationId 的设置,所以返回 undefined。
  • 组件执行时机先后问题:App 组件的 useEffect 在组件挂载后立即执行,调用 Auth.currentAuthenticatedUser() 获取用户对象;而孙子组件初始化并设置 localStorage 的操作,执行时机晚于 App 组件的这个 useEffect。当 App 中打印 result.storage.organizationId 时,localStorage 里还没有该值,自然读取不到;后续孙子组件完成设置后,你在控制台展开 result 对象,浏览器实时读取了更新后的 localStorage 内容,所以能看到 organizationId。
  • Amplify Storage 的动态绑定特性:你配置的 storage: browserStorage 与浏览器 localStorage 做了绑定,result.storage 并非静态对象,而是一个动态读取 localStorage 的代理接口。同步打印时 localStorage 无对应值,所以返回 undefined;之后孙子组件设置了 localStorage,展开对象时 result.storage 动态读取到最新内容,因此能看到该键值对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 09:25:05