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
相关产品推荐
相关产品推荐

