You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级compileSdkVersion至31后React Native应用启动崩溃

解决React Native 0.66.5升级targetSdkVersion到31后的启动崩溃问题

问题背景

将React Native 0.66.5项目的compileSdkVersion和targetSdkVersion升级到31后,应用编译成功但启动时崩溃,LogCat捕获到以下致命异常:

FATAL EXCEPTION: pool-3-thread-1 Process: com.myimportantprojectabc, PID: 9629
java.lang.IllegalArgumentException: com.myimportantprojectabc: Targeting S+ (version 31 and above)
requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
...
at androidx.work.impl.utils.ForceStopRunnable.getPendingIntent(ForceStopRunnable.java:285)

原因分析

Android 12(API 31)对PendingIntent的创建新增了强制要求:必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标记。而React Native 0.66.5默认依赖的旧版本androidx.work库未适配该要求,导致启动时初始化WorkManager时触发崩溃。

解决方案

方案一:升级androidx.work到适配API 31的版本(推荐)

修改项目根目录下的android/build.gradle文件:

  1. 在buildscript的ext块中添加指定work_version:
buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        ndkVersion = "20.1.5948944"
        androidXCore = "1.7.0"
        work_version = "2.7.1" // 适配API31的最低版本为2.7.0,这里推荐用2.7.1
    }
    // 其余配置保持不变
}
  1. 在allprojects的resolutionStrategy中强制指定androidx.work的版本:
allprojects {
     configurations.all {
          resolutionStrategy {
            force "com.facebook.react:react-native:" + REACT_NATIVE_VERSION
            // 强制使用指定版本的work库
            force "androidx.work:work-runtime:$work_version"
            force "androidx.work:work-runtime-ktx:$work_version"
          }
    }
    // 其余配置保持不变
}

方案二:禁用默认WorkManager初始化(不推荐,可能影响功能)

如果暂时无法升级work库,可通过AndroidManifest.xml禁用默认初始化:
在application标签内添加:

<application
  ...>
  <meta-data
    android:name="androidx.work.impl.WorkManagerInitializer"
    android:value="disabled" />
</application>

注意:此方法可能导致依赖WorkManager的后台功能失效,仅作为临时兼容方案。

验证步骤

  1. 清理Gradle缓存:
./gradlew clean
  1. 重新编译运行项目:
npx react-native run-android

内容的提问来源于stack exchange,提问作者Ravis Farooq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:01:22