Fix #10343 (legend crash with invalid layer)

Fixed the crash itself in the context menu, but also changed the behavior
to remove any invalid layers from project as currently there is no mechanism
for postponing handling of invalid layers after project load