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

Shopware 6管理端服务报错:TypeError: 无法读取undefined的getString属性

Shopware 6管理端服务注入报错:TypeError: Cannot read properties of undefined (reading 'getString')

问题描述

创建Shopware 6管理端服务后,注入Vue组件时出现TypeError: Cannot read properties of undefined (reading 'getString')错误,相关代码如下:

服务代码

// <administration root>core/service/ai.service.js 
export default class AIService {
    constructor(httpClient) {
        this.httpClient = httpClient;
    }

    getString() {
        return 'hello';
    }
}

服务初始化代码

// init/ai-service.init.js
import AIService from '../core/service/ai.service'

Shopware.Service().register('ai', (container) => {
    const initContainer = Shopware.Application.getContainer('init');
    return new AIService(initContainer.httpClient);
});

组件注入代码

Shopware.Component.register('example', {
    inject: ['ai'],

    created() {
        this.ai.getString().then(value => console.log(value))
    }
});

错误原因

  1. 初始化文件未被加载:Shopware 6不会自动识别自定义初始化文件,若未将其添加到构建流程或入口文件中,服务无法完成注册,导致组件注入时this.ai为undefined。
  2. 错误的异步调用:getString()方法返回普通字符串,并非Promise对象,调用.then()会触发额外错误,同时放大了this.ai未定义的问题。

解决方案

1. 确保初始化文件被正确加载

如果是自定义插件,需在插件的src/Resources/app/administration/webpack.config.js中配置入口,或直接在main.js中导入初始化文件:

// 在main.js中添加导入语句
import './init/ai-service.init.js';

若为核心代码修改,需确认文件被包含在Shopware的构建流程内。

2. 修正组件中的方法调用

去掉不必要的.then(),直接获取getString()的返回值:

Shopware.Component.register('example', {
    inject: ['ai'],

    created() {
        const value = this.ai.getString();
        console.log(value);
    }
});

3. 验证服务注册状态

在初始化文件中添加日志,确认服务是否成功注册:

// ai-service.init.js
import AIService from '../core/service/ai.service'

const serviceContainer = Shopware.Service();
serviceContainer.register('ai', (container) => {
    const initContainer = Shopware.Application.getContainer('init');
    const aiService = new AIService(initContainer.httpClient);
    console.log('AI Service 已注册:', aiService);
    return aiService;
});

打开浏览器控制台,查看是否有该日志输出,确认服务实例已创建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:52:54