鸿蒙应用开发实战【87】— 常见崩溃排查null指针与类型断言 鸿蒙应用开发实战【87】— 常见崩溃排查null指针与类型断言本文是「号码助手全栈开发系列」第 87 篇持续更新中…开源社区https://openharmonycrossplatform.csdn.net前言ArkTS 严格模式下空指针和类型断言是运行时崩溃的主要来源。号码助手项目在开发中遇到并解决了多类崩溃问题。本篇整理常见崩溃场景、根因分析和预防措施。本篇涵盖null 指针!.与?.选择、类型断言失败as风险、ResultSet 关闭与游标越界、undefined id 导致的数据库更新失败、Promise 未 catch 异常、页面销毁后更新 State 崩溃。一、null 指针崩溃1.1 非空断言?.vs 强制解包!.// ❌ 危险如果 card 为 null直接崩溃Text(this.card!.phone_number)// ✅ 安全使用 ?. 可选链Text(this.card?.phone_number??)// ✅ 安全提前 returnif(!this.card)returnText(this.card.phone_number)// 此处可安全使用 !1.2 项目中实际的 null 指针场景// CardDetailPageprivateasyncloadData():Promisevoid{try{constcardawaitCardDao.findById(this.cardId)if(!card){promptAction.showToast({message:卡号不存在或已被删除})this.getUIContext().getRouter().back()// null 时直接返回return}this.cardcard// 此后可安全使用 this.card!}catch(e){...}}1.3 undefined id 问题// ❌ 危险entity.id 可能为 undefinedawaitCardDao.deleteById(this.card!.id!)// 双重非空断言// ✅ 安全提前校验if(!this.card||this.card.idundefined)returnawaitCardDao.deleteById(this.card.id)二、类型断言失败2.1 as 的风险// 数据库中可能存储了非法值status:rs.getString(rs.getColumnIndex(status))asBindingStatus// 如果数据库返回 未知状态as 不会阻止崩溃// 方案parseRow 中加兜底constrawStatusrs.getString(rs.getColumnIndex(status))status:[使用中,待换绑,待注销,已停用].includes(rawStatus)?rawStatusasBindingStatus:使用中三、ResultSet 操作规范// ❌ 危险未检查行数直接读取constrsawaitstore.query(predicates,COLS)constidrs.getLong(rs.getColumnIndex(id))// 游标在-1位置// ✅ 正确先 goToFirstRow 再读取rs.goToFirstRow()constidrs.getLong(rs.getColumnIndex(id))// ✅ 或者检查 rowCountif(rs.rowCount0rs.goToFirstRow()){// 安全读取}rs.close()// 务必关闭四、页面销毁后更新 State// 场景异步回调在页面已销毁后尝试更新 StateprivateasyncdoBackup():Promisevoid{this.backingtruetry{// 异步操作}finally{// 如果页面已被销毁用户按了返回此处崩溃this.backingfalse// 崩溃Cannot update state after page destroyed}}预防在页面生命周期onPageHide或aboutToDisappear中取消待处理的异步操作。小结崩溃类型原因预防检测方式null 指针对象为 null 时用!解包提前校验 ?.??兜底编译时 lint类型断言as 转换不兼容类型parseRow 加兜底默认值单元测试ResultSet未 goToFirstRow 直接读取先检查 rowCount 再读取Code Reviewundefined id实体可选 idif (id undefined) return静态分析异步 State页面销毁后更新取消待处理异步操作运行时监控如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源openHarmony 跨平台社区https://openharmonycrossplatform.csdn.netHarmonyOS 官方文档https://developer.huawei.com/consumer/cn/doc/HarmonyOS hilog文档https://developer.huawei.com/consumer/cn/doc/harmonyos-references/hilogHarmonyOS testinghttps://developer.huawei.com/consumer/cn/doc/harmonyos-guides/unit-testArkTS 严格模式开发https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-strict-mode