解决 React Native 报错 Invariant Violation AppRegistry 未注册修复
排查 React Native 启动红屏报错 Invariant Violation: MyApp has not been registered,排查 app.json 与原生 getMainComponentName 命名一致性。
问题现象
在手机模拟器或真机启动 React Native 应用时,页面出现大红屏致命报错:
Invariant Violation: "MyApp" has not been registered.
This can happen if:
* Metro (the local dev server) is run from the wrong folder.
* A module failed to load due to an error and AppRegistry.registerComponent wasn't called.
触发根因
- 原生入口声明的根组件名称与 JS 注册名不匹配:Android 端
MainActivity.kt中的getMainComponentName()或 iOS 端moduleName与app.json中配置的name存在大小写或拼写差异; - Metro 打包服务端口被其它历史工程占用:当前手机连接的 Metro 服务实际上是在另一个目录启动的打包器,返回了不匹配的 JS Bundle;
- 根模块加载阶段发生语法错误中断执行,使得
AppRegistry.registerComponent(...)语句根本未能被执行到。
解决步骤
1. 核对 app.json 与原生入口工程名称一致性
检查 app.json 中的根名称:
{
"name": "MyApp",
"displayName": "MyApp"
}
在 Android MainActivity.kt 检查:
class MainActivity : ReactActivity() {
override fun getMainComponentName(): String = "MyApp"
}
在 iOS AppDelegate.mm 检查:
self.moduleName = @"MyApp";
确保三者字符串完全一致。
2. 重置 Metro 缓存并绑定当前工程
杀死冲突端口并重置缓存启动:
# 查找占用 8081 端口的旧进程并结束
lsof -i :8081 | awk 'NR>1 {print $2}' | xargs kill -9
# 纯净模式启动 Metro
npx react-native start --reset-cache
验证确认
重新触发应用打包并加载:
npx react-native run-android
# 或 npx react-native run-ios
设备正常拉取 JS Bundle 进度条并渲染出首屏 UI,红屏报错消失。


