How to stop execution of a function via add_action hook?

The usual way to add an action hook is more like this:

// ... some other code
do_action( 'my_action', $post_id );

// ...elsewhere
add_action( 'my_action', 'wpse405965_function' );
/**
 * Function hooked to my_action
 *
 * @param int $post_id The post ID.
 */
function wpse405965_function( $post_id ) {
    if ( 2 !== $post_id ) {
        echo $post_id;
    }
}

The way you’ve wrapped the do_action() inside a function confuses me. It seems extraneous.

Reference