React Native Web集成@sentry/react-native遇ErrorUtils未定义问题求助
React Native Web 中使用 @sentry/react-native 遇到 ErrorUtils 未定义的解决方案
方案一:加载Sentry前注入模拟的ErrorUtils
在Web端入口文件(如index.web.js)最顶部添加代码,模拟React Native的ErrorUtils核心实现,让Sentry能正常初始化:
// 必须在引入 @sentry/react-native 之前执行 if (typeof ErrorUtils === 'undefined') { global.ErrorUtils = { setGlobalHandler: (handler) => { // 监听全局脚本错误 window.onerror = (message, source, lineno, colno, error) => { handler(error || new Error(message)); return true; }; // 监听未处理的Promise拒绝 window.addEventListener('unhandledrejection', (event) => { handler(event.reason); }); }, getGlobalHandler: () => window.onerror, reportError: (error) => { console.error('ErrorUtils.reportError:', error); }, }; }
这个实现覆盖了Sentry依赖的核心方法,可临时解决Web端的报错问题。
方案二:按平台区分使用对应SDK(推荐)
官方更推荐针对Web端使用专门的@sentry/react SDK,通过平台判断加载不同的SDK:
import { Platform } from 'react-native'; if (Platform.OS === 'web') { import('@sentry/react').then(({ init }) => { init({ dsn: '你的Sentry DSN地址', // Web端专属配置项 environment: process.env.NODE_ENV, release: 'your-app-version@1.0.0', }); }); } else { import('@sentry/react-native').then(({ init }) => { init({ dsn: '你的Sentry DSN地址', // Native端配置项 enableAutoSessionTracking: true, }); }); }
这种方式能让Web端获得更适配的错误监控能力,彻底避免RN SDK在Web环境的兼容性问题。
方案三:禁用ReactNativeErrorHandlers集成
如果不想切换SDK或注入模拟函数,可以在初始化Sentry时移除导致报错的集成:
import * as Sentry from '@sentry/react-native'; Sentry.init({ dsn: '你的Sentry DSN地址', integrations: (integrations) => { // 过滤掉ReactNativeErrorHandlers集成 return integrations.filter(integration => integration.name !== 'ReactNativeErrorHandlers'); }, });
注意:此方案会丢失React Native专属的错误处理逻辑,Web端需自行补充全局错误监听,仅作为临时应急方案。
内容的提问来源于stack exchange,提问作者S.V.
相关产品推荐
相关产品推荐

