1.0.3: Typed property must not be accessed before initialization


I have a component with a public property that is initialized in the mount method. After I update to 1.0.3 I get the PHP 7.4 error that the property must not be accessed before initialization.

The error is triggered in the InteractsWithProperties trait on line 19.

Shouldn’t the mount method be called immediately after the instantiation?

1 Like

You will have to set a default value for typed properties of that type in Livewire instead of just declaring them.

public string $search = "";
public ?string $search = null;
public int $number = 0;

For anyone wondering why: With the typed properties in 7.4 they have a state of initialized and uninitialized, instead of the expected behavior of properties defaulting to a null value if there isn’t one assigned. In “regular” classes, the properties can maintain an uninitialized state, and this error is only thrown when you try to actually access it. Which all makes sense because the point of it all is to have stricter code.

There’s a few reasons why Livewire (and a portion of Laravel for that matter) is different than a textbook oop object. First, mount() should not be thought of as __construct(), and should be thought of closer to Laravel’s boot() method. The object has been built already, and some behind the scenes work has been done that makes Livewire work, before the mount() method is called. mount() is just the first method called in in the code you provide to Livewire.

In this case, the Livewire method being called getPublicPropertiesDefinedBySubClass() that is throwing this error is scanning all declared properties on the class, so if the property is in a uninitialized state, the error is getting thrown by php. Livewire has to know what public properties have been declared so when the server round trip is made, it can reassign those properties with the values that were contained/updated on the front end. This is part of the behind the scenes work that is done before it reaches the code you have written.

1 Like

Thanks. Figured it was something like that. The thing is this is very recent… My code worked fine until recently.

I know this is an old conversation however I wanted to know what happens when the variable that im trying to use happens to be an instance model. First I set this as public property public User $user; then just as the docs says I’ll be trying to “save” a user to the database:

    public function save()


As soon as I type a word I get this same message, Im wondering how to work around this issue when you have a Model instance binded in the public property and you cannot exactly set it to null or with an empty value. Version is 2.0