rotation.y flips when turning around x-axis

I’ve adapted a script from these forums to make an object rotate to face the mouse cursor, acting as if the screen and the relevant game object are on the same 2D plane. It does the job, rotating around X as I’d like it to, but it flips its Y rotation at the top and bottom extremes. In other words, when the mouse pointer crosses the centre of the screen from right to left, the Y rotation switches from 0 to 180 degrees and vice versa. This creates a visual problem in that the object keeps inverting and prevents me from having a reliable rotation value to build on for other effects.

Any insights would be greatly appreciated.

var mousePos : Vector3;
var target : Transform; //Assign to the object you want to rotate (self)
var objectPos : Vector3;
     
function Update (){
    mousePos = Input.mousePosition;
    mousePos.z = 0; //The distance between the camera and object
    objectPos = Camera.main.WorldToScreenPoint(target.position);
    mousePos.x = mousePos.x - objectPos.x;
    mousePos.y = mousePos.y - objectPos.y;
    transform.LookAt(mousePos);
    transform.position.z = 0;
}

Here a simple script to get an object to look at the mouse position:

function Update (){
    var mousePos = Input.mousePosition;
    //mousePos.z = Camera.main.nearClipPlane;
    mousePos.z = 5.0f;
    var lookPos : Vector3 = Camera.main.ScreenToWorldPoint(mousePos);
    transform.LookAt(lookPos);
}

mousePos.z is the distance in front of the camera you want project the point. The minimum should be nearClipPlane, since any object nearer would not be (in part) visible to the camera. The closer you set the z value to the position of the object, the greater the twisting of the object. For example if the camera was at -10 on the Z axis, and the object is at 0 on the z axis, a value of 9 would give far greater twisting than 3.