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

React集成AWS Amplify时检查用户状态出现未处理运行时错误

报错原因
  • 核心原因是你代码中导入的AmplifySignOut组件实际为undefined,在React中渲染undefined作为组件会直接抛出你遇到的类型无效错误。
  • 该问题通常由@aws-amplify/ui-react包的版本不匹配导致:v2及以上版本的@aws-amplify/ui-react已经移除了AmplifySignOut组件,按照旧版文档的导入方式导入该组件会得到undefined。
  • 额外潜在问题:你调用Auth.currentAuthenticatedUser()时没有捕获异常,如果当前用户未登录,该方法会抛出未处理的Promise错误。
解决方案

方案1:降级到旧版本包(兼容现有代码)

直接执行命令安装v1.x版本的UI包即可:

npm install @aws-amplify/ui-react@1.2.26

安装完成后重启开发服务,原有代码不需要修改即可正常运行。

方案2:适配新版本API(推荐)

按照新版@aws-amplify/ui-react的规范修改代码:

  1. 移除AmplifySignOut的导入,新版withAuthenticator包装后的组件会自动注入用户信息和登出方法,不需要自行调用接口获取用户状态。
  2. 直接通过组件props获取user和signOut方法即可。

修改后的代码如下:

import { withAuthenticator } from '@aws-amplify/ui-react'

function Profile({ user, signOut }) {
  if (!user) return null
  return (
    <>
      <h1 className="text-3xl font-semibold tracking-wide mt-6">Profile</h1>
      <h3 className="font-medium text-gray-500 my-2">Username: {user.username}</h3>
      <p className="text-sm text-gray-500 mb-6">Email: {user.attributes.email}</p>
      <button onClick={signOut}>退出登录</button>
    </>
  )
}

export default withAuthenticator(Profile)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:36:05