执行TypeScript代码时遇forEach读取未定义属性错误求助
错误信息
TypeError: Cannot read properties of undefined (reading 'forEach')
at ScapprovalPaymentEventComponent.(http://localhost:50000/main.js?v=23.1.0+Build-17.02-1904:6102:33)
at step (http://localhost:50000/main.js?v=23.1.0+Build-17.02-1904:5940:23)
at Object.next (http://localhost:50000/main.js?v=23.1.0+Build-17.02-1904:5921:53)
at http://localhost:50000/main.js?v=23.1.0+Build-17.02-1904:5915:71
at new ZoneAwarePromise (http://localhost:50000/polyfills.js?v=23.1.0+Build-17.02-1904:8553:29)
at push../ClientApp/app/components/forms/scapproval-payment-event/scapproval-payment-event.component.ts.__awaiter (http://localhost:50000/main.js?v=23.1.0+Build-17.02-1904:5911:12)
at push../ClientApp/app/components/forms/scapproval-payment-event/scapproval-payment-event.component.ts.ScapprovalPaymentEventComponent.initializeControls (http://localhost:50000/main.js?v=23.1.0+Build-17.02-1904:6058:16)
相关代码
this.totalCount = response.total_rows; this.bookmark = response.bookmark; if (isPaginationCall && this.approvedForms && this.approvedForms.length > 0) { paymentForms.forEach(x => this.approvedForms.push(x)); } else { this.approvedForms = paymentForms; } this.onShowRecordChange(); setTimeout(() => { this.spinner.hide("MONITORPAYMENT"); }, 0);
问题原因
错误直接指向paymentForms.forEach(...)这一行,说明**paymentForms的值为undefined**,对undefined调用数组方法forEach会触发类型错误。
常见触发场景:
- 接口返回的
response未包含预期的paymentForms字段,导致变量未被正确赋值 - 前置逻辑中
paymentForms的初始化或赋值流程失败,最终变为undefined
解决方案
需在调用forEach前校验paymentForms的有效性,同时处理其为undefined的情况,以下是几种可行修改方式:
方式一:添加非空与数组类型校验
this.totalCount = response.total_rows; this.bookmark = response.bookmark; if (isPaginationCall && this.approvedForms && this.approvedForms.length > 0) { // 先确认paymentForms存在且为数组,再执行遍历 if (paymentForms && Array.isArray(paymentForms)) { paymentForms.forEach(x => this.approvedForms.push(x)); } } else { // 若paymentForms为undefined,默认赋值为空数组避免后续逻辑出错 this.approvedForms = paymentForms || []; } this.onShowRecordChange(); setTimeout(() => { this.spinner.hide("MONITORPAYMENT"); }, 0);
方式二:使用可选链操作符(ES2020+支持)
如果项目支持ES2020或更高版本,可通过可选链简化校验逻辑:
this.totalCount = response.total_rows; this.bookmark = response.bookmark; if (isPaginationCall && this.approvedForms && this.approvedForms.length > 0) { // 可选链语法:若paymentForms为undefined则自动跳过遍历 paymentForms?.forEach(x => this.approvedForms.push(x)); } else { this.approvedForms = paymentForms || []; } this.onShowRecordChange(); setTimeout(() => { this.spinner.hide("MONITORPAYMENT"); }, 0);
额外建议
- 检查接口返回的数据结构,和后端约定
paymentForms字段始终返回数组(空数组或有效数据),避免返回undefined - 给
paymentForms添加TypeScript类型定义,明确其为数组类型,在编译阶段提前发现潜在问题
内容的提问来源于stack exchange,提问作者Indhumadhi K V

