React Native生产环境中Amplify Auth.signIn()无法触发,本地正常
React Native Amplify Auth.signIn 在EAS生产构建中无法触发(本地正常)
问题场景
- 技术栈:React Native(Expo)+ AWS Amplify Authentication(auth分类)
- 异常现象:
Auth.signIn({ username, password })通过eas build --profile preview --platform android构建的生产包中毫无反应,但本地调试完全正常;Auth.signUp()可正常执行,用户能成功存入DynamoDB,所有依赖包已更新至最新版本。
用户代码片段
AmplifyService
SignIn = async (username: string, password: string) => { return await Auth.signIn({ username, password }); }; SignUpUser = async (username: string, password: string, email:string, name:string) => { return await Auth.signUp({ username, password, attributes: { email, name } }); };
组件调用代码
const [isUserAuthenticated, setIsUserAuthenticated] = useState(false); useEffect(() => { SignUpUser(); }, []); const SignUpUser = () => { AmplifyService.SignIn("test", "password0") .then(() => { setIsUserAuthenticated(true); }).catch((err) => { // 假设用户不存在时执行注册 AmplifyService.SignUpUser("test","password0","email@xx.xx","test").then(() => { AmplifyService.SignIn(username, password).then(() => { setIsUserAuthenticated(true); }); }); }); };
排查与解决方案
1. 校验Amplify环境配置一致性
本地调试和EAS构建可能使用了不同的Amplify环境配置,需确认:
- EAS构建过程中是否正确注入了生产环境的
aws-exports.js,可在构建脚本中添加配置校验步骤,或在App启动时打印配置信息(生产包可借助日志工具查看)。 - 确保
aws-exports.js中的Auth核心配置(region、userPoolId、userPoolWebClientId)与生产环境完全匹配,未误用本地测试配置。
2. 完善错误捕获与日志输出
当前代码仅处理了“用户不存在”的异常,但生产环境可能存在网络错误、配置错误等其他问题,需补充完整的错误捕获:
const SignUpUser = () => { AmplifyService.SignIn("test", "password0") .then(() => setIsUserAuthenticated(true)) .catch((signInErr) => { console.error('SignIn失败详情:', signInErr); // 生产环境用持久化日志工具输出 // 仅当明确是用户不存在异常时才执行注册 if (signInErr.name === 'UserNotExistException') { AmplifyService.SignUpUser("test","password0","email@xx.xx","test") .then(() => AmplifyService.SignIn("test", "password0")) .then(() => setIsUserAuthenticated(true)) .catch((signUpErr) => console.error('注册或二次登录失败:', signUpErr)); } }); };
注:生产环境中console.log可能被打包工具移除,建议使用expo-logger实现日志持久化,方便定位问题。
3. 清理构建缓存并校验依赖
EAS构建的缓存可能导致依赖缺失,重新构建时添加清理缓存参数:
eas build --profile preview --platform android --clear-cache
同时确认@aws-amplify/auth、@aws-amplify/core等核心依赖在生产构建中已正确安装。
4. 检查Android网络权限
确保AndroidManifest.xml中已声明网络权限(Expo默认会添加,但自定义配置可能被移除):
<uses-permission android:name="android.permission.INTERNET"/>
无网络权限会导致Auth请求静默失败。
5. 验证参数与用户状态
- 确认生产环境中传递给
Auth.signIn的username和password参数值正确,无格式错误或变量未定义问题(比如二次登录时的username、password变量需与注册时一致)。 - App启动时校验当前用户状态,避免残留会话影响登录流程:
import { Auth } from '@aws-amplify/auth'; // 初始化Amplify后执行 Auth.currentAuthenticatedUser({ bypassCache: true }) .then(user => console.log('当前已登录用户:', user)) .catch(() => console.log('无已登录用户'));
内容的提问来源于stack exchange,提问作者DevQc
相关产品推荐
相关产品推荐

