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

执行下述代码时出现Cannot read property 'renderError' of null错误咨询

排查 "Cannot read property 'renderError' of null" 错误及代码修复方案

嘿,我来帮你拆解这个问题!首先看到你遇到的Cannot read property 'renderError' of null错误,通常意味着你在某个null对象上尝试调用renderError方法,结合你提供的DataSource代码,我们先从代码本身的问题入手,再解决上下文的问题:

1. 代码里的核心错误:API响应判断逻辑错误+拼写失误

先看你的DataSource.makeup方法,这里有两个关键问题:

  • 拼写错误:你写了responseJson.arrray,多打了一个r,正确拼写应该是array——但这还不是最关键的问题!
  • API响应结构判断错误:你调用的美妆API返回的直接是产品数组,不是一个包含array属性的对象。比如请求product_type=lipstick时,返回的是[{...}, {...}, ...]这样的数组,根本没有array字段,所以你的判断if(responseJson.arrray)永远不会成立,会直接进入Promise.reject分支,触发后续的错误处理逻辑。

2. 修复后的DataSource代码

我帮你调整了逻辑,同时增加了请求成功的判断(比如HTTP状态码不是200的情况):

import makeups from './makeups.js'; 

class DataSource {
  static makeup(keyword) {
    return fetch(`http://makeup-api.herokuapp.com/api/v1/products.json?product_type=${keyword}`)
      .then(response => {
        // 先检查请求是否成功(比如404、500等状态)
        if (!response.ok) {
          throw new Error('请求失败,请检查网络或API状态');
        }
        return response.json();
      })
      .then(responseJson => {
        // API返回的直接是产品数组,判断数组是否有内容
        if (responseJson.length > 0) {
          return Promise.resolve(responseJson);
        } else {
          return Promise.reject(`${keyword} 未找到相关产品`);
        }
      })
      .catch(error => {
        // 统一处理请求过程中的错误,也可以让上层调用者自行处理
        return Promise.reject(error.message);
      });
  }
}

export default DataSource;

3. 解决renderError的null问题

现在来说那个Cannot read property 'renderError' of null错误,这大概率是你调用DataSource.makeup()时,错误处理函数里的this指向不对导致的。比如你可能是这样调用的:

// 错误示例:这里的this在catch回调里可能变成了null/undefined
DataSource.makeup('lipstick')
  .then(result => { /* 处理结果 */ })
  .catch(error => {
    this.renderError(error);
  });

解决办法很简单,确保renderError的调用上下文正确:

  • 方法一:提前保存this的引用
    const that = this;
    DataSource.makeup('lipstick')
      .then(result => { /* 处理结果 */ })
      .catch(error => {
        that.renderError(error);
      });
    
  • 方法二:用箭头函数绑定上下文(箭头函数会继承外层的this)
    DataSource.makeup('lipstick')
      .then(result => { /* 处理结果 */ })
      .catch(error => this.renderError(error));
    

总结

先修复DataSource里的API响应判断逻辑和拼写错误,再检查调用处的this上下文是否正确,这样就能解决你遇到的两个问题啦!

内容的提问来源于stack exchange,提问作者Ferry Irmansyah

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 11:23:15