Fatal error: Call to a member function user() on boolean

Fatal error: Call to a member function user() on boolean

我必须在 view 中使用 loggedIn 用户数据,因此创建了一个变量 AUTH_USER[= beforeRender 函数中的 AppController 中的 32=]。

82     public function beforeRender(Event $event)
83     {
84          if ($this->Auth->user('id')) {
85          $this->set('AUTH_USER', $this->Auth->user());
86          }
87          ...
88          ...
89     }

每当出现错误时,它不会显示实际错误,而是显示以下没有样式格式的错误

Fatal error: Uncaught Error: Call to a member function user() on boolean in /path_to_app/src/Controller/AppController.php:84 
Stack trace: #0 /path_to_app/src/Controller/ErrorController.php(54): App\Controller\AppController->beforeRender(Object(Cake\Event\Event)) 
#1 /path_to_app/vendor/cakephp/cakephp/src/Event/EventManager.php(422): App\Controller\ErrorController->beforeRender(Object(Cake\Event\Event)) 
#2 /path_to_app/vendor/cakephp/cakephp/src/Event/EventManager.php(391): Cake\Event\EventManager->_callListener(Array, Object(Cake\Event\Event)) 
#3 /path_to_app/vendor/cakephp/cakephp/src/Event/EventDispatcherTrait.php(78): Cake\Event\EventManager->dispatch(Object(Cake\Event\Event)) 
#4 /path_to_app/vendor/cakephp/cakephp/src/Controller/ in /path_to_app/src/Controller/AppController.php on line 84

删除行 84 - 86 显示实际错误

Edit 2

在 AppController initialize() 中加载 Auth 组件的代码

我编写了以下代码来加载 AUTH 组件。

$this->loadComponent('Auth', [
   'authenticate' => [
      'Form' => [
         'userModel' => 'Admins',
            'fields' => [
               'username' => 'email', 
               'password' => 'password'
             ]
         ]
      ],
      'loginAction' => [
         'controller' => 'Admins',
         'action' => 'index'
      ],
      'loginRedirect' => [
         'controller' => 'Admins',
         'action' => 'contentList'
       ],
      'authError' => 'Did you really think you are allowed to see that?',
      'logoutAction' => [
         'controller' => 'Pages',
         'action' => 'home'
       ]
]);

您没有为要检查的 if 语句提供正确的 ID。您必须通过函数的参数发送登录用户的 ID,然后在 if 语句中检查该 ID。

我遇到了同样的错误,如果您将此行添加到 beforeRender() 它应该可以工作:

$this->loadComponent('Auth');

可能是您没有正确初始化 initialize() 函数中的组件。