Closure scope issue: The script tried to execute a method or access a property of an incomplete object

I have an issue with the following code.

<?php

include_once ('vendor/autoload.php');

use SpatieAsyncPool;

$pool = Pool::create();

for($i = 0; $i < 100; $i++) {
    $task = new ExpensiveTask($i);
    $pool->add(function () use ($task) {
        return $task->delayedProcess();
    })->then(function ($output) {
        print "Completed task: " . $output;
    })->catch(function (Throwable $exception) {
        print $exception->getMessage();
    })->timeout(function () {
        print "timeout";
    });
}

$pool->wait();

class ExpensiveTask {

    private $taskId;

    public function __construct(int $index) 
   {
       $this->taskId = $index;
   }

   public function delayedProcess() {
       sleep(1);
       return $this->taskId;
   }
}

On executing the above code I’m getting the following 500 error. Not sure why it’s happening.

PHP Fatal error:  {closure}(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "ExpensiveTask" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide an autoloader to load the class definition in closure://function () use ($task) {
        return $task->delayedProcess();
    } on line 3

How I can fix this, I’m new to PHP closures. Even I tried to declare the class before using it but getting the same error.

Answer

Added the class in composer autoload and is working fine.

"autoload": {
    "files": ["src/ExpensiveTask.php"]
}

Thanks.