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

ES6构造函数传递对象至目标文件后属性undefined问题求助

解决ChildClass中method1无法访问auth属性的问题

我来帮你排查和解决这个问题,主要有两个关键点需要修复:

1. 修复Service类中的错误super()调用

你的Service类没有继承任何父类,但在constructor里调用了super(),这会直接导致运行时错误,中断代码执行。如果这个类不需要继承其他类,请直接删除super():

// ServiceFile.js 修复后
import ChildClass from 'ChildClass';
export default class Service {
  constructor(cookie, token) {
    // 删掉不必要的super()
    this.auth = { cookie: 'XXX', token: 'XXX' };
    this.checkout = new ChildClass(this.auth);
  }
  async serviceMethod(data) {
    return await this.checkout.method1(data);
  };
}

如果你的Service类原本需要继承某个类(比如React组件),请补上extends声明,比如:class Service extends SomeParentClass,这样super()调用才合法。

2. 修复axios.post的调用格式错误

你当前的axios.post写法不符合官方规范,导致headers配置没有被正确应用,同时可能让你误以为是this.auth的属性访问问题。axios.post的正确参数格式是:
axios.post(url[, data[, config]])

你需要补充请求的URL,并调整参数顺序:

// ChildClassFile.js 修复后
class ChildClass {
  constructor(auth) {
    this.auth = auth;
    console.log("ChildClass -> constructor -> this.auth", this.auth); // 这里能拿到值就说明auth传递正常
  }
  async method1(data) {
    // 补充你的API地址,调整参数顺序
    return await axios.post('/your-target-api-url', data, {
      headers: { token: this.auth.token, cookie: this.auth.cookie },
    });
  };
}

额外的this绑定保险(可选)

如果修复上述问题后仍然遇到this指向异常的情况,可以通过以下方式确保method1中的this始终指向ChildClass实例:

方式一:在constructor中绑定this

class ChildClass {
  constructor(auth) {
    this.auth = auth;
    this.method1 = this.method1.bind(this); // 手动绑定this
  }
  // ... 其他代码不变
}

方式二:使用箭头函数定义method1

class ChildClass {
  constructor(auth) {
    this.auth = auth;
  }
  // 用箭头函数定义方法,自动绑定实例this
  method1 = async (data) => {
    return await axios.post('/your-target-api-url', data, {
      headers: { token: this.auth.token, cookie: this.auth.cookie },
    });
  };
}

按照以上步骤修复后,你应该就能在method1中正常访问this.auth的属性了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 23:52:30