调用API时出现Uncaught TypeError: Cannot read properties of undefined (reading 'then')错误
问题解决:Uncaught TypeError: Cannot read properties of undefined (reading 'then')
你的问题核心是getFilms函数没有返回Promise对象。虽然内部的fetch请求能正常执行、数据也能打印,但整个函数执行完后默认返回undefined,当你在外部调用getFilms().then(...)时,自然会触发读取undefined的then方法的错误。
修复方法很简单,把fetch调用的Promise链返回出去即可:
function getFilms() { // 加上return,将fetch返回的Promise链传递给函数调用者 return fetch('https://ghibliapi.herokuapp.com/films') .then((response) => response.json()) .then((data) => { console.log(data); return data; }); } export default getFilms;
修改后getFilms()调用会返回一个Promise,你就能正常用.then()处理返回的数据了。
内容的提问来源于stack exchange,提问作者Marcel Guimarães
相关产品推荐
相关产品推荐

