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

JavaScript使用Fetch加载JSON数据时出现Cannot read 'then' of undefined错误

问题原因与解决方案

错误原因

你的fetchUsers函数没有返回fetch调用生成的Promise对象。函数内部执行了fetch操作,但没有把这个Promise链返回出去,导致调用fetchUsers()时得到的是undefined——而undefined没有.then()方法,所以会抛出「Uncaught TypeError: Cannot read properties of undefined (reading 'then')」这个错误。

修正后的代码

核心修正:让fetchUsers返回Promise

function fetchUsers() {
  // 关键:添加return,把fetch的Promise链返回给调用者
  return fetch('users.json')
    .then(response => response.json())
    .then(data => {
      const users = data.users.map(user => new User(user.username, user.password));
      return users
    })
    .catch(error => console.error(error));
}

完整修正后的JavaScript代码

import { User } from './user.js';

document.addEventListener('DOMContentLoaded', function () {
  var submitBtn = document.getElementById('submit-btn');
  submitBtn.addEventListener('click', function (event) {
    event.preventDefault();
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    fetchUsers()
      .then(users => console.log(users))
      .catch(error => console.error(error));
  });

  function fetchUsers() {
    return fetch('users.json')
      .then(response => response.json())
      .then(data => {
        const users = data.users.map(user => new User(user.username, user.password));
        return users
      })
      .catch(error => console.error(error));
  }
});

额外优化提示

你的User类存在语义错误:getAge()方法实际返回的是密码,建议修改方法名以避免混淆:

export class User {
  constructor(username, password) {
    this.username = username;
    this.password = password;
  }

  getName() {
    return this.username;
  }

  getPassword() { // 修正方法名,匹配返回值语义
    return this.password;
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:03:12