findLoads方法报TypeError: Cannot read properties of undefined (reading 'filter')求助
报错根因定位
报错TypeError: Cannot read properties of undefined (reading 'filter')的触发原因是调用filter方法的对象responseObj.searchResults为undefined,通常由以下场景导致:
- 后端接口返回数据结构不符合预期,无匹配查询结果时未返回
searchResults字段,或字段名拼写不一致 - 接口请求异常返回错误结构,未携带
searchResults字段 - 前端接口请求参数错误,导致后端返回异常结构
修复方案
在调用filter前增加非空兜底,同时补充接口错误处理、修正加载动画关闭的时机,修改后的完整findLoads方法如下:
findLoads(){ // 补充loggedInUser的可选链判断,避免该对象未初始化时触发同类报错 if(this.loggedInUser?.userFullySetupFlag === 0 || this.loggedInUser?.businessFullySetupFlag === 0){ swal( 'Incomplete Profile', 'To find loads and bid, all the details inside User Profile (My Profile) and Business Profile (My Business) must be completed.', 'error' ) return; } this.shipmentService.filterLoads(this.currentLoadBoardSearch).subscribe({ next: (responseObj) => { // 兜底处理:searchResults不存在时默认赋值为空数组 const searchResults = responseObj?.searchResults || [] responseObj.searchResults = searchResults.filter(function(value, index, arr){ return value.loadNumber <= responseObj.loadNumber; }); this.filteredLoads = responseObj.searchResults; console.log("Load Results:", responseObj); }, error: (err) => { console.error("查询运单失败:", err) // 可根据业务需要补充错误弹窗提示 this.filteredLoads = [] }, complete: () => { // 加载动画统一在请求结束后关闭,无论成功失败,避免提前隐藏的问题 this.spinner.hide(); } }) }
额外排查建议
- 先在浏览器控制台的网络面板查看接口返回的实际数据结构,确认
searchResults字段的命名是否和代码一致 - 如果确认后端无匹配数据时不会返回该字段,上述代码的兜底逻辑已经可以覆盖该场景
内容的提问来源于stack exchange,提问作者Utkarsh
相关产品推荐
相关产品推荐

