React Native开发Native模块时遇RCTEventEmitter.receiveTouches注册错误
你遇到的错误信息如下:
ExceptionsManager.js:151 Invariant Violation: Failed to call into JavaScript module method RCTEventEmitter.receiveTouches(). Module has not been registered as callable. Registered callable JavaScript modules (n = 0): . A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native. reactConsoleErrorHandler @ ExceptionsManager.js:151 registerError @ LogBox.js:187 console.error @ LogBox.js:67 overrideMethod @ backend.js:2082 reportException @ ExceptionsManager.js:95 handleException @ ExceptionsManager.js:141 handleError @ setUpErrorHandling.js:24 reportFatalError @ error-guard.js:49 __guard @ MessageQueue.js:369 callFunctionReturnFlushedQueue @ MessageQueue.js:112 (anonymous) @ debuggerWorker.js:69
以下是针对性的排查和解决步骤:
确认入口文件配置正确
iOS端:打开AppDelegate.m/AppDelegate.swift,检查jsBundleURLForBundleRoot参数是否指向正确的入口文件名(默认是"index",入口为index.tsx也无需修改后缀)。
Android端:打开MainApplication.java/MainApplication.kt,确认getJSMainModuleName()方法返回的是正确的入口文件名(比如"index")。彻底清除缓存并重建项目
- 执行JS端缓存重置:
npx react-native start --reset-cache - iOS端:在Xcode中点击
Product->Clean Build Folder,之后重新运行项目 - Android端:进入项目的
android目录,执行./gradlew clean,再重新编译运行
- 执行JS端缓存重置:
检查自定义Native模块的注册逻辑
因为你正在开发Native模块,大概率是模块注册或事件发射器实现有问题:- iOS模块:确保模块类正确调用了
RCT_EXPORT_MODULE(),如果是事件发射器,要继承RCTEventEmitter并实现supportedEvents方法,同时在init或didMount中完成事件注册。 - Android模块:确认模块类继承了
ReactContextBaseJavaModule,并且在MainApplication的getPackages()方法中添加了该模块实例;如果是事件发射器,要正确获取ReactContext的JSModule<RCTEventEmitter>,并确保事件发送逻辑没有提前执行。
- iOS模块:确保模块类正确调用了
验证JS bundle完整性
手动重新生成JS bundle测试:
iOS:npx react-native bundle --entry-file index.js --platform ios --dev false --bundle-output ios/main.jsbundle --assets-dest ios,之后修改AppDelegate加载本地bundle,看是否能正常运行。
Android:npx react-native bundle --entry-file index.js --platform android --dev false --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res,再重新编译。排查初始化阶段的异常
暂时移除你开发的Native模块,运行基础React Native项目,如果能正常启动,说明问题出在你的自定义模块中。再逐步添加模块代码,定位到具体哪部分初始化逻辑导致加载失败。
内容的提问来源于stack exchange,提问作者Matrix

