You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular升级后报Cannot read properties of null (reading 'toISOString')错误排查

问题原因

这个报错的直接诱因是Angular Material版本从v7升级到v12之后的API行为变更:

  • Angular Material v7及更早版本的日期选择器过滤器函数,永远不会传入null作为参数,原有代码没有判空逻辑也能正常运行
  • Angular Material v9+重构了日期选择器的核心逻辑,在组件初始化、日期值清空、范围选择边界校验等场景下,会主动给过滤器函数传入null值,此时直接调用calendarDate.toISOString()就会触发空指针报错
修复方案

直接在函数开头补充空值判断即可,空值场景直接返回false(表示该日期不可选)即可,修改后代码如下:

this.miceBirthdayFilter = (calendarDate: Date): boolean => {
  // 新增空值判断
  if (!calendarDate) return false;
  let birthDates = [];
  this.uniqueValuesForEachAttribute['subject_birth_date'].forEach(date => {
    birthDates.push(date);
  });
  console.log("miceBirthdayFilter in Session " + birthDates.length)
  console.log("calendarDate in miceBirthdayFilter in Session " + calendarDate)
  return birthDates.includes(calendarDate.toISOString().substring(0, 10));
};
可选优化建议
  • 当前代码中birthDates数组每次调用过滤器都会重新生成,会造成不必要的性能损耗,建议提前在组件初始化阶段一次性生成缓存,不需要每次执行过滤器都遍历uniqueValuesForEachAttribute['subject_birth_date']
  • 检查项目中所有其他的日期选择器过滤器函数,全部补充相同的空值判断逻辑,避免其他页面出现同类报错

内容的提问来源于stack exchange,提问作者Carlos Ortiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 10:54:04