Pagination of custom post type leads to 404 error

Paste this function to your functions.php file

if ( ! function_exists( 'custom_pagination' ) ) {
    function custom_pagination( $query_args ) {
        $big = 999999999; // need an unlikely integer
        $pages = paginate_links( array(
                'base'      => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                'format'    => '?paged=%#%',
                'current'   => max( 1, get_query_var( 'paged' ) ),
                'total'     => $query_args->max_num_pages,
                'prev_next' => false,
                'type'      => 'array',
                'prev_next' => true,
                'prev_text' => __('«'),
                'next_text' => __('»'),
            ) );
        if ( is_array( $pages ) ) {
            $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
            echo '<ul class="pagination">';
            foreach ( $pages as $page ) {
                    echo "<li>$page</li>";
            }
            echo '</ul>';
        }
    }
}

Then on your custom post loop page write the loop as

$args = [
    'post_type'      => 'post',
    'posts_per_page' => get_option('posts_per_page'),
];

$query = new WP_Query( $args );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // You content goes here
    }
    custom_pagination( $query );
    wp_reset_postdata();
}

This works fine for me.