解决新版RN 热更新报错:recreateReactContextInBackground
一、报错描述
React-native 集成 react-native-code-push 报错
java.lang.AssertionError: recreateReactContextInBackground should only be called after the initial createReactContextInBackground call.
二、原因分析
这是因为你使用了 rn 版本(0.76~到最新的0.79.3),此版本默认启用了TurboModules 新架构,新架构存在 bug:在安卓上无法清除rn内存中的上下文缓存,也就是说不支持实时热更新,除非应用杀死内存重启否则 rn 永远使用旧的不会变。
三、解决方案
1、关闭新架构
修改android 根目录下gradle.properties
文件,将此字段置为 false:
newArchEnabled=false
备注:只改动上面配置即可,SoLoader.init(this, OpenSourceMergedSoMapping)不要改
2、启用新架构
只能做到下次启动 app更新
备注:TurboModules新架构决定了此特性,如果你有清理TurboModules 缓存的方法也请同步我下。
需修改代码如下(修改npm源码神器patch-package):
1、CodePush.java
这里写死防止回滚
boolean updateIsLoading = pendingUpdate.getBoolean(CodePushConstants.PENDING_UPDATE_IS_LOADING_KEY);
// 如果启用newArchEnabled:此行写死避免代码回滚
updateIsLoading = false;
2、CodePushNativeModule.java
注释掉重新创建上下文方法,防止报错退出 App
instanceManager.recreateReactContextInBackground();