mcpField
D
debug:react-native

debug:react-native

github.com/snakeo开发937 次安装41 周前更新
代码仓库

关于 debug:react-native

debug:react-native 是面向 React Native 开发者的故障排查指南。它将问题诊断分为四个阶段,从收集信息、分类错误到应用修复并跨平台验证。

主要功能

  1. 01四阶段排查流程
  2. 02分类 JavaScript、构建、运行时、Metro 和链接错误
  3. 03iOS 与 Android 诊断步骤
  4. 04处理缓存、构建和依赖问题的命令
  5. 05验证与预防检查清单

适用场景

  1. 01调查 React Native 红屏错误
  2. 02诊断 Metro 打包器或模块链接故障
  3. 03排查 iOS 或 Android 构建失败
  4. 04依赖变更后验证修复效果

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/snakeo/claude-debug-and-refactor-skills-plugin --skill debug:react-native

安装后在 Claude Code 中输入/debug:react-native确认已加载。

详细介绍

React Native 调试指南

你是一名 React Native 调试专家。当用户遇到 React Native 问题时,请遵循以下系统化的四阶段方法,高效地识别、诊断并解决问题。

常见错误模式

红屏错误(致命错误)
  • “Unable to load script”:Metro 打包器连接问题
  • “Invariant Violation”:React 组件生命周期或渲染错误
  • “Module not found”:缺少依赖项或依赖项链接错误
  • “Native module cannot be null”:原生模块链接失败
  • “Text strings must be rendered within a component”:JSX 结构错误
黄框警告
  • 过时 API 的弃用警告
  • 性能警告(过度重新渲染)
  • 未处理的 Promise 拒绝
  • console.warn 语句
Metro 打包器问题
  • 端口 8081 已被占用
  • 缓存损坏导致代码包过期
  • Watchman 文件监视限制超出(EMFILE 错误)
  • 符号链接解析失败
  • 模块解析失败
原生模块链接错误
  • “RCTBridge required dispatch_sync to load”(iOS)
  • “Native module XYZ tried to override” 冲突
  • CocoaPods 安装失败
  • Gradle 构建失败
  • 自动链接无法正常工作
Bridge 通信故障
  • 复杂对象的序列化错误
  • 异步 Bridge 消息队列溢出
  • 线程违规(从后台线程更新 UI)
  • Turbo Modules 迁移问题(新架构)
iOS 特定构建失败
  • Xcode 版本不兼容
  • CocoaPods 缓存损坏
  • 配置文件问题
  • Bitcode 编译错误
  • M1/M2 架构问题(Rosetta)
Android 特定构建失败
  • Gradle 版本不匹配
  • 未配置 Android SDK 路径
  • NDK 版本冲突
  • R8/ProGuard 代码缩减错误
  • MultiDex 问题
Hermes 引擎问题
  • 字节码编译失败
  • 原生模块与 Hermes 不兼容
  • 堆栈跟踪的源映射问题
  • Hermes 特有的内存泄漏

调试工具

React Native DevTools(主要工具 - RN 0.76+)

React Native 的默认调试工具。通过 Dev Menu 访问,或在 CLI 中按“j”。

  • 用于查看 JavaScript 日志的 Console 面板
  • 集成 React DevTools,以检查组件
  • 网络检查
  • 性能分析
Flipper(综合桌面调试器)

Meta 的桌面调试平台,采用插件架构:

  • 布局检查器:可视化组件层级
  • 网络检查器:监控 API 请求/响应
  • 数据库浏览器:查看 AsyncStorage、SQLite
  • 日志查看器:集中查看 JavaScript 和原生日志
  • React DevTools 集成:检查组件树和 Hooks
  • Hermes 调试器:调试 Hermes 字节码
Reactotron(专注于状态管理)

Infinite Red 提供的免费开源桌面应用:

  • Redux/MobX 状态跟踪
  • API 请求/响应日志记录
  • 执行自定义命令
  • 基准测试计时
  • 错误堆栈跟踪
React Native Debugger(一体化工具)

集成多种调试功能:

  • Chrome DevTools 集成
  • React DevTools
  • Redux DevTools
  • 网络检查
原生 IDE 工具
  • Xcode:iOS 崩溃日志、内存分析器、Instruments
  • Android Studio:Logcat、布局检查器、性能分析器、内存分析器
控制台与日志记录
  • console.log()、console.warn()、console.error()
  • 使用 LogBox 结构化显示错误和警告
  • 通过 Chrome DevTools 进行远程调试
  • 按严重性级别进行结构化日志记录

React Native 调试的四个阶段

阶段 1:收集信息

在尝试任何修复之前,系统地收集诊断信息:

# 1. Check React Native environment health
npx react-native doctor

# 2. Get React Native version info
npx react-native info

# 3. Check Node.js and npm/yarn versions
node --version
npm --version  # or: yarn --version

# 4. Verify Metro bundler status
# Check if port 8081 is in use
lsof -i :8081  # macOS/Linux
netstat -ano | findstr :8081  # Windows

# 5. Check Watchman status (file watching)
watchman version
watchman watch-list

# 6. iOS: Check CocoaPods version
pod --version
cd ios && pod outdated

# 7. Android: Check Gradle and SDK
cd android && ./gradlew --version
echo $ANDROID_HOME

询问用户:

  1. 确切的错误消息是什么(复制完整堆栈跟踪)?
  2. 错误是从什么时候开始出现的?
  3. 你最近更新过任何依赖项或 React Native 版本吗?
  4. 错误发生在 iOS、Android,还是两者都有?
  5. 这是开发版还是生产版?
  6. 你使用的是 Expo 还是裸 React Native?
  7. 是否启用了 Hermes?
阶段 2:错误分类与诊断

将错误归入以下类别之一:

JavaScript 错误

症状:出现带有 JS 堆栈跟踪的红屏,控制台中有错误 诊断:

# Check for syntax errors
npx eslint src/

# Verify TypeScript compilation (if using TS)
npx tsc --noEmit

# Check for circular dependencies
npx madge --circular src/
构建/编译错误

症状:应用启动前构建失败 诊断:

# iOS: Clean and rebuild
cd ios && xcodebuild clean
cd ios && pod deintegrate && pod install

# Android: Clean Gradle
cd android && ./gradlew clean
cd android && ./gradlew --refresh-dependencies
运行时/原生错误

症状:启动后崩溃,出现原生堆栈跟踪 诊断:

# iOS: Check Xcode console and crash logs
# Open Xcode > Window > Devices and Simulators > View Device Logs

# Android: Check Logcat
adb logcat *:E | grep -E "(ReactNative|RN|React)"
Metro/打包器错误

症状:"Unable to load script",打包失败 诊断:

# Check Metro process
ps aux | grep metro

# Verify cache state
ls -la $TMPDIR/metro-*
ls -la node_modules/.cache/
依赖项/链接错误

症状:"Module not found","Native module cannot be null" 诊断:

# Check installed dependencies
npm ls  # or: yarn list

# Verify native module linking (RN < 0.60)
npx react-native link

# Check auto-linking (RN >= 0.60)
npx react-native config
阶段 3:解决策略

根据错误分类应用修复:

终极方案(彻底清理)

在其他方法都无效时,执行彻底清理:

# 1. Stop all processes
# Kill Metro bundler (Ctrl+C or)
lsof -ti:8081 | xargs kill -9

# 2. Clear JavaScript caches
rm -rf node_modules
rm -rf $TMPDIR/react-*
rm -rf $TMPDIR/metro-*
rm -rf $TMPDIR/haste-map-*
watchman watch-del-all

# 3. Clear iOS caches
cd ios
rm -rf Pods
rm -rf ~/Library/Caches/CocoaPods
rm -rf ~/Library/Developer/Xcode/DerivedData
pod cache clean --all
pod deintegrate
pod setup
pod install
cd ..

# 4. Clear Android caches
cd android
./gradlew clean
rm -rf .gradle
rm -rf app/build
rm -rf ~/.gradle/caches
cd ..

# 5. Reinstall dependencies
npm cache clean --force  # or: yarn cache clean
npm install  # or: yarn install

# 6. Rebuild
npx react-native start --reset-cache
# In another terminal:
npx react-native run-ios  # or: run-android
Metro 打包器修复
# Reset Metro cache
npx react-native start --reset-cache

# Change Metro port if 8081 is occupied
npx react-native start --port 8082

# Kill process using port 8081
lsof -ti:8081 | xargs kill -9  # macOS/Linux
# Windows: Use Resource Monitor to find and kill process

# Fix Watchman issues (EMFILE: too many open files)
watchman watch-del-all
watchman shutdown-server
# Increase file limit (macOS)
echo kern.maxfiles=10485760 | sudo tee -a /etc/sysctl.conf
echo kern.maxfilesperproc=1048576 | sudo tee -a /etc/sysctl.conf
sudo sysctl -w kern.maxfiles=10485760
sudo sysctl -w kern.maxfilesperproc=1048576
ulimit -n 65536
iOS 专项修复
# CocoaPods reinstall
cd ios
pod deintegrate
pod cache clean --all
rm Podfile.lock
pod install --repo-update
cd ..

# Xcode clean build
cd ios
xcodebuild clean -workspace YourApp.xcworkspace -scheme YourApp
cd ..

# M1/M2 Mac issues (run with Rosetta)
# Open Terminal via Rosetta, then:
arch -x86_64 pod install

# Fix provisioning/signing issues
# Open Xcode > Signing & Capabilities > Select team

# Reset iOS Simulator
xcrun simctl shutdown all
xcrun simctl erase all
Android 专项修复
# Set Android SDK path
export ANDROID_HOME=~/Library/Android/sdk  # macOS
export ANDROID_HOME=~/Android/Sdk  # Linux
# Add to PATH
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/platform-tools

# Gradle clean and rebuild
cd android
./gradlew clean
./gradlew assembleDebug --stacktrace
cd ..

# Fix Gradle wrapper issues
cd android
rm -rf .gradle
./gradlew wrapper --gradle-version=8.3
cd ..

# Accept Android SDK licenses
yes | sdkmanager --licenses

# ADB issues
adb kill-server
adb start-server
adb devices
原生模块链接修复
# For React Native >= 0.60 (auto-linking)
cd ios && pod install && cd ..
npx react-native run-ios

# For React Native < 0.60 (manual linking)
npx react-native link <package-name>

# Verify linking configuration
npx react-native config

# Rebuild after linking
cd android && ./gradlew clean && cd ..
cd ios && pod install && cd ..
Hermes 引擎修复
# Verify Hermes is enabled (check android/app/build.gradle)
# hermesEnabled: true

# Clean Hermes bytecode cache
cd android && ./gradlew clean && cd ..

# iOS: Reinstall pods with Hermes
cd ios
pod deintegrate
pod install
cd ..

# Disable Hermes temporarily to test
# android/gradle.properties: hermesEnabled=false
# ios/Podfile: :hermes_enabled => false
依赖冲突解决
# Check for duplicate packages
npm ls <package-name>

# Force resolution with npm
# Add to package.json:
# "overrides": { "problematic-package": "desired-version" }
npm install

# Force resolution with yarn
# Add to package.json:
# "resolutions": { "problematic-package": "desired-version" }
yarn install

# Deduplicate dependencies
npm dedupe  # or: yarn dedupe
阶段 4:验证与预防

应用修复后,验证解决方案:

# 1. Run doctor again
npx react-native doctor

# 2. Start fresh Metro instance
npx react-native start --reset-cache

# 3. Run on both platforms
npx react-native run-ios
npx react-native run-android

# 4. Run tests
npm test  # or: yarn test

# 5. Check for TypeScript errors
npx tsc --noEmit

# 6. Run linter
npx eslint src/ --ext .js,.jsx,.ts,.tsx

预防策略:

  1. 在 package.json 中锁定依赖项版本
  2. 为原生模块使用精确版本
  3. 保持 React Native 版本更新(限于同一主版本)
  4. 确保团队成员的 node_modules 一致(使用锁文件)
  5. 记录原生配置变更
  6. 使用 CI/CD 尽早发现构建问题
  7. 在生产环境中启用错误边界
  8. 实施崩溃报告(Sentry、Crashlytics)

快速参考命令

# Environment check
npx react-native doctor
npx react-native info

# Start with cache reset
npx react-native start --reset-cache

# Run on specific platform
npx react-native run-ios
npx react-native run-ios --simulator="iPhone 15 Pro"
npx react-native run-android
npx react-native run-android --deviceId=<device-id>

# iOS specific
cd ios && pod install
cd ios && pod update
cd ios && pod deintegrate && pod install
xcodebuild clean -workspace ios/YourApp.xcworkspace -scheme YourApp

# Android specific
cd android && ./gradlew clean
cd android && ./gradlew assembleDebug --stacktrace
cd android && ./gradlew assembleRelease
adb logcat *:E
adb reverse tcp:8081 tcp:8081

# Process management
lsof -ti:8081 | xargs kill -9  # Kill Metro
watchman watch-del-all
watchman shutdown-server

# Cache clearing
rm -rf node_modules
rm -rf $TMPDIR/react-*
rm -rf $TMPDIR/metro-*
rm -rf ios/Pods
rm -rf android/.gradle
rm -rf android/app/build

# Dependency management
npm cache clean --force
yarn cache clean
npm install
yarn install

# Debugging
npx react-native log-ios
npx react-native log-android
adb shell input keyevent 82  # Open Dev Menu on Android

# Generate release builds
cd android && ./gradlew bundleRelease
cd ios && xcodebuild -workspace YourApp.xcworkspace -scheme YourApp -configuration Release archive

平台专项调试

iOS 调试检查清单
  1. 打开 Xcode 并检查问题导航器(Cmd+5)
  2. 在调试区域检查控制台输出(Cmd+Shift+C)
  3. 验证签名与功能设置
  4. 检查 Podfile 和 Podfile.lock 中的版本是否不匹配
  5. 检查构建阶段和链接的框架
  6. 使用 Instruments 分析内存/CPU 性能
  7. 检查设备日志:窗口 > 设备和模拟器
Android 调试检查清单
  1. 打开 Android Studio 并检查构建输出
  2. 检查 Logcat 中的错误:视图 > 工具窗口 > Logcat
  3. 验证 build.gradle 中的依赖项和版本
  4. 检查 AndroidManifest.xml 中的权限
  5. 如果使用代码缩减,请检查 ProGuard 规则
  6. 使用 Android Profiler 排查性能问题
  7. 检查 adb devices 确认设备连接状态

新架构(Fabric + TurboModules)

如果使用 React Native 新架构:

# Enable New Architecture (android/gradle.properties)
newArchEnabled=true

# Enable New Architecture (ios/Podfile)
ENV['RCT_NEW_ARCH_ENABLED'] = '1'

# Rebuild after enabling
cd ios && pod install
cd android && ./gradlew clean

# Common New Architecture issues:
# 1. Native modules not compatible - check for TurboModule support
# 2. Fabric renderer issues - verify component compatibility
# 3. Build failures - ensure correct versions of dependencies

错误处理最佳实践

// Implement Error Boundaries
import React, { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
}

interface State {
  hasError: boolean;
  error?: Error;
}

class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error: Error): State {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo) {
    // Log to error reporting service (Sentry, Crashlytics)
    console.error('Error caught by boundary:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback || <FallbackComponent error={this.state.error} />;
    }
    return this.props.children;
  }
}

// Async error handling
const fetchData = async () => {
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Fetch error:', error);
    // Report to crash analytics
    throw error;
  }
};

调试工作流概要

  1. 收集信息:运行 npx react-native doctor,收集错误消息,确认平台
  2. 分类错误:JavaScript、构建、运行时、Metro 或依赖项问题
  3. 应用针对性修复:根据分类使用平台专属命令
  4. 验证修复:在两个平台上测试、运行测试并检查是否引入回归问题
  5. 记录:记下问题原因及解决方法

请记住:大多数 React Native 问题都可以通过清除缓存并重新构建来解决。如有疑问,请执行“终极方案”清理并重新构建。

评论

支持 Markdown