404 on paginated blog pages

I managed to work around this issue. I recently updated my site to WordPress 5.7 and was getting 404 Errors on every page except the home page. After a lot of debugging I found out that wp-includes/class-wp.php was setting the is_404 variable because of a missing comment <!--nextpage--> in the $post->post_content. (Line 694)

I tried disabling all the plugins on the site. Using the Twenty Twenty-One theme. Re-saving the Permalinks. Creating a new page to test it. Nothing worked. So I did this on my theme’s function.php:

add_filter("pre_handle_404", "no_nextpage_fix", 10, 2);
function no_nextpage_fix($return, $wp_query)
{
    $next="<!--nextpage-->";
    $post = isset( $wp_query->post ) ? $wp_query->post : null;
    if ($post && false === strpos( $post->post_content, $next ))
    {
        $post->post_content .= $next;
    }
    return $return;
}