Magento执行InstallData时报Call to a member function dispatch() on null错误
问题定位与修复方案
报错Error: Call to a member function dispatch() on null的核心根因是:自定义模型StateMaster重写构造方法时未调用父类AbstractModel的构造方法,导致模型依赖的事件管理器实例为空,执行save操作触发事件分发时调用失败。
以下是具体修复步骤:
1. 修复Model/StateMaster.php
补充父类构造所需的依赖并调用父构造,补全后代码如下:
namespace Navien\Custom\Model; use \Magento\Framework\Model\AbstractModel; use \Magento\Framework\Model\Context; use \Magento\Framework\Registry; use \Psr\Log\LoggerInterface; class StateMaster extends AbstractModel { protected $_logger; public function __construct( Context $context, Registry $registry, LoggerInterface $logger, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [] ) { $this->_logger = $logger; // 必须调用父类构造初始化事件管理器等核心依赖 parent::__construct($context, $registry, $resource, $resourceCollection, $data); $this->_init('Navien\Custom\Model\ResourceModel\StateMaster'); } }
2. 优化Model/StateData.php(推荐)
移除不规范的ObjectManager直接调用,改用Magento标准的依赖注入方式,代码可调整为:
namespace Navien\Custom\Model; use Navien\Custom\Model\StateMasterFactory; use Navien\Custom\Model\ResourceModel\StateMaster\CollectionFactory; use Psr\Log\LoggerInterface; class StateData { protected $_logger; protected $_stateMasterFactory; protected $_stateCollectionFactory; public function __construct( LoggerInterface $logger, StateMasterFactory $stateMasterFactory, CollectionFactory $stateCollectionFactory ) { $this->_logger = $logger; $this->_stateMasterFactory = $stateMasterFactory; $this->_stateCollectionFactory = $stateCollectionFactory; } public function insertStates($states) { if(empty($states)) return; // 直接查询已存在的州编码,效率更高 $existingCodes = $this->_stateCollectionFactory->create()->getColumnValues('code'); foreach($states as $state) { if(!in_array($state['code'], $existingCodes)) { $stateMaster = $this->_stateMasterFactory->create(); $stateMaster->setData($state)->save(); } } } }
3. 简化Collection.php(可选,无特殊需求时可操作)
移除不必要的依赖注入,保留默认逻辑即可:
namespace Navien\Custom\Model\ResourceModel\StateMaster; class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection { protected function _construct() { $this->_init('Navien\Custom\Model\StateMaster','Navien\Custom\Model\ResourceModel\StateMaster'); } }
验证生效步骤
- 进入数据库删除
setup_module表中module字段为Navien_Custom的记录 - 执行命令
php bin/magento setup:upgrade - 检查
navien_states表是否已成功插入对应州数据
内容的提问来源于stack exchange,提问作者Sanjay Goswami
相关产品推荐
相关产品推荐

