React Native TypeScript中数字0被识别为NaN问题求助
React Native(Android)调试模式下数字0显示为NaN的问题
问题说明
用React Native(Android)+ TypeScript开发时,遇到数字0在调试工具(console.log、VSCode检查器)里被显示为NaN的情况,数组映射、TypeScript枚举场景都存在这个问题,但实际运行逻辑中值是正常的——比如用模板字符串输出时,能正确识别0为number类型。
环境版本:
- TypeScript v4.7.4
- RN 0.69.2
- React 18
代码及现象
数组映射示例
const R = [...Array(4).keys()]; R.map((_i, key) => { console.log(_i, key); });
输出:
NaN NaN // 实际是0,调试显示为NaN 1 1 2 2 3 3
模板字符串验证
R.forEach(i => { console.log(`value is : ${i} is ${typeof i}`); console.log(i); });
输出:
value is : 0 is number NaN value is : 1 is number 1 value is : 2 is number 2 value is : 3 is number 3
环境详情
output for 'npx react-native info' info Fetching system and libraries information... System: OS: Windows 10 10.0.22000 CPU: (12) x64 Intel(R) Core(TM) i7-8700K CPU @ 3.70GHz Memory: 11.90 GB / 31.92 GB Binaries: Node: 18.6.0 - C:\Program Files\nodejs\node.EXE Yarn: 1.22.15 - C:\Program Files (x86)\Yarn\bin\yarn.CMD npm: 8.13.2 - C:\Program Files\nodejs\npm.CMD Watchman: Not Found SDKs: Android SDK: API Levels: 31, 33 Build Tools: 30.0.3, 33.0.0 System Images: android-32 | Google APIs Intel x86 Atom_64, android-33 | Google APIs Intel x86 Atom_64, android-33 | Google Play Intel x86 Atom_64 Android NDK: Not Found Windows SDK: AllowAllTrustedApps: Enabled AllowDevelopmentWithoutDevLicense: Enabled Versions: 10.0.19041.0 IDEs: Android Studio: AI-212.5712.43.2112.8609683 Visual Studio: 17.1.32328.378 (Visual Studio Community 2022), 16.11.32106.194 (Visual Studio Community 2019) Languages: Java: 17.0.1 - C:\Program Files\Java\jdk-17.0.1\bin\javac.EXE npmPackages: @react-native-community/cli: Not Found react: 18.0.0 => 18.0.0 react-native: 0.69.2 => 0.69.2 react-native-windows: Not Found npmGlobalPackages: *react-native*: Not Found
解决办法
这是React Native旧版本调试器的序列化bug,不影响代码实际运行,只是调试显示异常,可通过以下方式处理:
- 升级RN版本:RN 0.69.x存在这个调试器问题,后续0.70+版本已修复,建议升级到稳定版(比如0.70.6及以上)。
- 调试时包装输出:暂时无法升级的话,自定义日志函数,把数字转成字符串输出:
const debugLog = (val: any) => { console.log(typeof val === 'number' ? `${val}` : val); }; // 使用示例 R.forEach(i => debugLog(i)); - 切换调试工具:用Chrome DevTools替代VSCode检查器,部分开发者反馈这个工具不会出现0显示为NaN的问题。
- 调整调试器配置:如果用Hermes引擎,尝试关闭远程调试的
Enable Hermes Debugging选项,或重置调试器配置,可能缓解问题。
内容的提问来源于stack exchange,提问作者jack
相关产品推荐
相关产品推荐

