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

ReactJS报错:TypeError: Object(...)(...) is undefined 问题排查

问题分析与解决方案

兄弟,我一眼就揪出你这个报错的根源了——newImage函数没有返回Promise对象,导致你在handleImageChange里调用newImage(...).then(...)时,newImage(...)的返回值是undefined,自然没法调用.then()方法,才会抛出TypeError: Object(...)(...) is undefined的错误。

为什么会出现这种“报错但请求仍成功”的矛盾情况?

看你的newImage函数代码:你内部调用了axios.post发起请求,但没有把axios返回的Promise给return出去。你在.then()和.catch()回调里写的return true/false,只是回调函数自身的返回值,并不会让newImage函数本身返回一个Promise。

这就导致两个结果:

  1. axios请求已经被触发执行了,所以服务器能收到请求并返回响应;
  2. 但newImage(...)返回的是undefined,后续的.then()调用自然会报错。

修复方案

只需要给newImage函数加上一个return,让它返回整个axios的Promise链就行:

function newImage(image_ID, image, imgType, type) {
  var url = ...;
  const header = { headers: { 'Content-Type': imgType } };
  // 关键:return 整个axios.post的Promise链
  return axios.post(url, image, header)
    .then(function (response) {
      if(response.status === 200) {
        if(type !== '1') sessionStorage.setItem('avatar', image_ID);
        console.log("Image uploaded!");
        return true;
      } else {
        return false;
      }
    })
    .catch(function (error) {
      console.log(`Image could not be uploaded due to:\n${error}`);
      return false;
    });
}

修改后,newImage函数会返回一个标准的Promise对象,你在handleImageChange里的.then()就能正常执行,不会再出现报错了。另外你代码里的其他部分(比如saveCropped里的setTimeout绑定this的写法)都是没问题的,不用调整。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:16:44