Expo开启Chrome远程调试时useAuthRequest抛出原生模块同步调用错误
问题描述
这应该是一个常见问题,但我尚未找到其他遇到相同问题的用户。
我使用的是Expo SDK 42,完全按照官方文档示例写法调用Expo的AuthSession.useAuthRequest,我们的实现逻辑与以下示例代码基本一致:
// 以下是Expo提供的示例代码,我们的实现逻辑基本一致 const [request, response, promptAsync] = useAuthRequest( { clientId: 'CLIENT_ID', scopes: ['openid', 'profile', 'email', 'offline_access'], redirectUri: makeRedirectUri({ scheme: 'your.app' }), }, discovery ); return ( <Button disabled={!request} title="Login" onPress={() => { promptAsync(); }} /> );
每当开启Chrome远程调试时,调用useAuthRequest就会抛出以下阻塞错误:
Invariant Violation: Calling synchronous methods on native modules is not supported in Chrome. Consider providing alternative methods to expose this method in debug mode, e.g. by exposing constants ahead-of-time.
注释掉useAuthRequest的调用后错误就会消失,基本可以确定是该API导致的问题。但注释该接口后我无法调试应用中身份验证之后的逻辑。
绕过方案
- 替换调试工具
放弃Chrome远程调试,改用Expo Go内置开发菜单的「调试JS」能力,配合React Native Debugger或Hermes引擎自带的调试工具使用即可。Expo SDK 42对Hermes的支持已经稳定,Hermes调试模式下不会触发同步调用原生模块的限制,无需修改业务代码即可正常调试全链路逻辑。 - 开发阶段Mock身份验证逻辑
通过环境变量判断当前调试状态,开发模式下跳过useAuthRequest调用,硬编码登录成功的返回结果,直接执行后续业务逻辑。参考实现如下:
const isDebugMode = __DEV__ && !process.env.NO_MOCK_AUTH; let request, response, promptAsync; if (isDebugMode) { request = { valid: true }; promptAsync = () => { // 自定义模拟登录成功的返回参数 response = { type: 'success', params: { access_token: 'mock_token_xxxxxx', id_token: 'mock_id_token_xxxxxx', refresh_token: 'mock_refresh_token_xxxxxx' } }; }; } else { // 非调试模式走原有登录逻辑 [request, response, promptAsync] = useAuthRequest( { clientId: 'CLIENT_ID', scopes: ['openid', 'profile', 'email', 'offline_access'], redirectUri: makeRedirectUri({ scheme: 'your.app' }), }, discovery ); }
- 升级Expo SDK版本
该问题属于Expo SDK 42中AuthSession模块的已知缺陷,SDK 44及以上版本已经修复了调试模式下的兼容问题,升级对应版本后无需额外修改即可在Chrome远程调试下正常调用该接口。
内容的提问来源于stack exchange,提问作者Guillermo Moratorio
相关产品推荐
相关产品推荐

